• Vamsi
  • SMARTIE
  • 1299 Points
  • Member since 2015


  • Chatter
    Feed
  • 33
    Best Answers
  • 4
    Likes Received
  • 6
    Likes Given
  • 34
    Questions
  • 385
    Replies
does schedule job runs exactly at given time that we have mentioned?
When a User record is deactivated, we need to auto-populate any existing Opty records with their active manager (as noted in the user record), so those Opty records always have an active owner and are not sitting in limbo with a de-active user.  We want to automate this process.  
Any suggestions on best approach? 
Thank you, 
T
 
trigger contactTrigger on Contact (before insert,before Update) {
  if(RecursiveTrigger.isFirst){
       if(Trigger.isInsert || Trigger.isUpdate){
           List<String>  emailList = new List<String>();
           for(Contact c:Trigger.new){
             emailList.add(c.Email);
           }
           
           System.debug('email====>>>>'+emailList);
           
           Map<String,User> userMap = new Map<String,User>();
           List<User>  objUser = [Select id,email,FullPhotoUrl from User where Email in: emailList];
           for(User u:objUser){
            if(u.FullPhotoUrl != null)
               userMap.put(u.email,u);
           }
           List<Contact> objContactList = new List<Contact>();
           for(Contact c:Trigger.new){
            if(userMap.containskey(c.Email))
            
             c.Photo_Url__c = userMap.get(c.Email).FullPhotoUrl;
              
           }
           
       }
  }
}
  • June 07, 2018
  • Like
  • 0
Hi ,I have 2 objects "Positions" and "Employment Websites" having many to many relationship between them with "Job Posting" as a junction object.
->I have a case "C1" on "Position" 
->Position "P1" is posted to 3 Employement Websites "W1" ,"W2" and "W3"
->My requirement is to show case "C1" on Employement Website "W1" ,"W2" and "W3"

I have written a trigger for the above requirement but i am stuck
Objects :
Position
Employment Websites
Job Posting (Junction object for Position and Employement Websites)
CaseRelatedList( junction object between case and employement websites)
case (look up to Position)
I am trying to copy case related list from Position to Employment Websites .
Trigger :
trigger CloneCaseRelatedList on Case (after insert) {
    set<string> posId = new set<string>();
    Map<string,Job_Posting__c> posEmpWebsite = new Map<String,Job_Posting__c>();
    if(Trigger.isInsert)
    {
        for(Case c : Trigger.new)
        {
            posId.add(c.Position__c);
                system.debug(posId);
        }
        
    }
    for(Job_Posting__c j : [Select Position__c ,Employment_Website__c from Job_Posting__c where Position__c in : posId ])
    {
        posEmpWebsite.put(j.Position__c, j);
        system.debug(posEmpWebsite);
    }
    //I am stuck at this point How I can loop through all employmemt websites that position have
        
    }
1.I have created CaseRelatedList as a junction object for Employement Website and Case
2.Created trigger on case and from there I am getting positions
3.finding employemnt websites related to position through junction object 'Job Posting'
4.Need to loop through result of step 3. 
How can I loop through it so that I can insert case and employment website on junction object caseRelatedList.
Thanks in advance!!
Hi Guys,

I'm trying to build a Visualforce page on the opportunity record that allows users to update a few fields on the parent account. I have built the visualforce page, but can't get the newly input values to save back to the account. I'm fairly sure that Opportunity should be the standard controller and I'll need an extension. That's the part I'm having some trouble on.

Can someone point me in the right direction on how I'd accomplish this?

Thanks,
Nick
Error message: "Error: Compile Error: Expression cannot be assigned at line 208 column 36"

Objective: I want to assign two different values to two different fields based on one conditional statement (programmatically) 

Code #1:

The code below works as expected but when I tried to add "&&" in Code #2 the code didn't not run.
 
// Determine coverage 
        
        if (insuranceType == 'BLA') {
             l.Insurance_type__c = 'Bla bla' l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(NonAcceptedPlans.contains(groupName)) {
             l.Insurance_type__c = 'Bla bla Bla bla';
        } else if(planDescription == '') {
             l.Insurance_type__c = 'TTT';
        } else {l.Insurance_type__c = 'Bla bla Bla bla Bla bla';}

Code #2:

When adding "&&" to my output part of the conditional statement the code stops working. I get an message: "
Error: Compile Error: Expression cannot be assigned at line 208 column 36"
 
// Determine coverage 
        
        if (insuranceType == 'BLA') {
             l.Insurance_type__c = 'Bla bla' l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(NonAcceptedPlans.contains(groupName)) {
             l.Insurance_type__c = 'Bla bla Bla bla' && l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(planDescription == '') {
             l.Insurance_type__c = 'TTT' && l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else {l.Insurance_type__c = 'Bla bla Bla bla Bla bla' && l.Qualification_message__c = 'Bla bla Bla blaBla bla";}
Hi, 

  I want to update entitlement fields from opportunitylines below is the code written not sure what the issue is it is not firring the update. Please suggest me the change.
 
trigger update_entitlement_product on OpportunityLineItem (after insert, after update) {

   system.debug('Opportunity Line Items Trigger Started.....');

   EntitlementUtil.UpdateEntitlementDate(trigger.new);

}
public with sharing class EntitlementUtil {

public static void UpdateEntitlementDate(List<OpportunityLineItem> newLst){

 set<id> oppid = new set<id>();
 list<entitlement> ent = new list<entitlement>();
 
  for(OpportunityLineItem opp: newLst){
   oppid.add(opp.id);
  }
  
 for(opportunity ops: [select NS_Start_Date_Min__c,NS_End_Date_Max__c from opportunity where id in :oppid]){
    system.debug('Opportunity Lines NS_Start_Date_Min__c :' + ops.NS_Start_Date_Min__c);
    system.debug('Opportunity Lines NS_End_Date_Max__c :' + ops.NS_End_Date_Max__c);
    
   for(entitlement etl : [select Opportunity__c,StartDate,EndDate from Entitlement where Opportunity__c in :oppid]){
    system.debug('Entitlement StartDate :' + etl.StartDate);
    system.debug('Entitlement EndDate :' + etl.EndDate);
    
      etl.StartDate = ops.NS_Start_Date_Min__c;
      etl.EndDate = ops.NS_End_Date_Max__c;
      ent.add(etl);
    }  
  }
 
  if(ent.size() > 0){
    system.debug('Entitlement dates are updated');
    update ent;
  }
  
}
}
Thanks
SD

 
  • June 01, 2018
  • Like
  • 0
I am trying to figure out how to have a if statement on a visualforce page check for two words in a text field. If the conditions are true display a message. I cant firgure out how to do this correctly to work. Below is the code to the field that does not work. Any help would be greatly appreciated.
 
<div class="lost message" style="display:{!IF(AND(CONTAINS(Opportunity.Describe_what_you_need_quoted__c , "Acme"), CONTAINS(Opportunity.Describe_what_you_need_quoted__c , "Inc")),"","none")}" >
      <h2>Opportunity:This is an ACME Opportunity!              
 </h2>
    </div>

 
  • May 31, 2018
  • Like
  • 0
I am new to SalesForce.  I have created my first Apex Class.  The goal of the class is to read through all ccrz__E_Order__c that are in 'Order Submitted' status.  For each order, read the items.  If all items are currently in 'Received' status, then update the status on the order to 'Order Received'.  I want this to be a batch process ran daily.

Following questions being a first time creator of an Apex Class.
  • Is the best way to trigger this process to run by going into Apex Class and Schedule Apex?  Or is there a more appropriate way to schedule?
  • When testing, I have used Developers Console and executed the class.  However, I run into limits.  Even when I have scheduled in our test environments, i have hit limits.  There are only a couple hundred orders in this status but it hits Too many SOQL queries system limit exception.  Is there a way to test the entire process w/o exceeding these limits?  Are they the same limits when going to production?  When testing I enter specific orders (you'll see commented out line below in the code), but when i read all orders i am hitting these limits.
  • Is there a system log that i can write totals too?  As you can see on the code below i have written beginning / ending / total information into the debug log.  But when going to production, i will comment these out - is there a traditional way to look at this kind of information in a salesforce log.  
I am including the code i have created and appreciate any feedback since this is my first attempt.

Thanks in advance for any advise.  

Dan

/*
 * @Name: Batch_OrderStatus
 * @Author: Dan Norfleet
 * Updates : 02/12/2018 - Dan Norfleet - Created Apex Class
 */
    global class Batch_OrderStatus Implements Schedulable
    {
      global void execute(SchedulableContext sc)
      {
        execute();
      }

      global void execute() 
      {
          System.debug('Batch_OrderStatus BEGIN');
          //  Create a list of Orders in status of 'Order Submitted'
          List<ccrz__E_Order__c> orders = 
                [SELECT Id, Name, ccrz__orderstatus__c 
                FROM ccrz__E_Order__c 
                WHERE ccrz__orderstatus__c = 'Order Submitted'];
//                WHERE ccrz__orderstatus__c = 'Order Submitted' AND Name = 'O-0000112447'];
          Integer total_orders_cnt = 0;
          Integer update_cnt = 0;
          Integer notupdated_cnt = 0;
          String status_received = 'Received';
          String status_order_received = 'Order Received';
          
          // Loop through the list of orders
          for(ccrz__E_Order__c ord : orders)
          { 
            total_orders_cnt = total_orders_cnt + 1;
            String order_id = ord.Id;
            // For each order, see how many items are in 'Received' status
            integer ItemsReceived = 
                    [SELECT COUNT() 
                    FROM ccrz__E_OrderItem__c 
                    WHERE ccrz__orderitemstatus__c = :status_received
                    AND ccrz__order__c = :order_id];
          
            integer ItemsNOTReceived = 
                    [SELECT COUNT() 
                    FROM ccrz__E_OrderItem__c 
                    WHERE ccrz__orderitemstatus__c != :status_received
                    AND ccrz__order__c = :order_id];
          
            if (ItemsReceived > 0)
                    { 
                if (ItemsNOTReceived == 0)
                        { 
                        ord.ccrz__orderstatus__c = status_order_received;
                        System.debug('    UPDATE Order - ID = ' + order_id + ' / Order Name = ' + ord.Name + ' / Items Received = ' + ItemsReceived + ' / ItemsNOTReceived = ' + ItemsNOTReceived);
                        update_cnt = update_cnt + 1;
                        update orders;
                        }
                    else
                        {
                        notupdated_cnt = notupdated_cnt + 1;
                        }
                    }
                
          }
          System.debug('TOTAL ORDERS IN SUBMITTED STATUS = ' + total_orders_cnt);
          System.debug('TOTAL UPDATED = ' + update_cnt);
          System.debug('TOTAL NOTUPDATED = ' + notupdated_cnt);
          System.debug('Batch_OrderStatus END');
      }
}
i have created a student object (child object ) which is in master detail relationship with Course object (parent ) and Student object is not visible in OWD. Why is this? If i want to edit OWD settings of Student object how is that possible.?
I need help writing a validation rule in Accounts that works like this:
If the Creator User has the Business_Unit_c field equal to "TSEB", then theCommercial_DiscountC field must be filled in. And if the Commercial_discount_c field is equal to "Yes", then the Discount_C field must also be filled in.
I have an example class I've just created for illustravive purposes that updates an acount name via a remote action.

I need to be able to write a test class to cover it, and it also needs to contain a system assert/assertequals?

I have written the test class but how do I cover it with a system assert?

Method:
@RemoteAction
global static void updateAccountName (String supplierId, String newName) {

    Account acc = [Select Id, Name From Account Where Id = : supplierId];

    acc.name = newName;
    
    update acc;

}
Test class:
@isTest
public class updateSupplierTest { 

	static testMethod void test () {

        updateAccount con = new updateAccount();

    	//Create an Account
        List<Account> accts = new List<Account>();
        Account b = new Account(Name='Test Buyer',type = 'Account');
        accts.add(b);
        insert accts;

        //Remote actions
        updateAccount.updateAccount(r.id, 'New Account Name');
        System.assertEquals(????); 

    }

}

Thanks
 
  • November 06, 2017
  • Like
  • 0
Hi Guyz,

I just want to create one simple vvalidation rule for a picklist value,

I am inserting a Library Name , once i fill the name, then there is Location with different picklist value.
For Eg: If user enter a name as "Mumbai Library"(Name Would be anything everytime), then location i would be selecting as "Mumbai", records get saved. but while editing the same record,it should not make me change to other location rather than Mumbai...
how it can be done...

I have wriiten below formula, but its not working as per my requirement

AND( ISPICKVAL( Location__c , "Mumbai"), NOT(ISBLANK( Name )) )

please help me to sort out

Regards
Pranav Shah

 
I have a trigger that updates a lookup field based on the value of a text field.  It's working great with the bulk uploads I'm doing, except when the bulk uploads reference the same record for lookup.  The lookup field (Customer Product Mix) populates on the first record, but fails to do so on subsequent records only when the same lookup record is referenced.

User-added image

Here is the code we're using, which I thought was bulkified since all other records populate just fine on a bulk upload.  Any help would be greatly appreciated.
 
trigger UpdateCustomerProductMix on Sales_Order_Line_Item__c (before insert, before update ){
 
    Map<String, Sales_Order_Line_Item__c> CPMToSOLIMap = new Map<String, Sales_Order_Line_Item__c>();

    for(Sales_Order_Line_Item__c soli:Trigger.new)
    {
        CPMToSOLIMap.put(soli.Customer_Product_Mix_UploadID_HIDDEN__c, soli);
 
    }
 
    List<Customer_Product_Mix__c> cpmLst = [SELECT ID, Name FROM Customer_Product_Mix__c where Name in :CPMToSOLIMap.keySet()];
 
    for(Customer_Product_Mix__c cpm : cpmLst){
        CPMToSOLIMap.get(cpm.Name). Customer_Product_Mix__c = cpm.ID;
    }
}



 
  • September 25, 2017
  • Like
  • 0
Hi,
       There is 2 custom object A & B, it's in a master-detail relationship. From the 3rd object, there is 2 lookup field to object A & B. I need to display records in B based on the record in lookup field to object A.
Hello,
I have created a custom object that we use to track different issues. Just like any custom object, I have the notes and attachements related list on there. On the object, there is a multi-select picklist field that contains a few different values. I wrote the following apex trigger to send an email notification when a new NOTE is added. The email will be sent to specific address based upon the value in the muli-select picklist. I am trying to figure out how to add a secuence to the subject line. So everytime a note is added the subject shows that it is the first, third, eighth, etc. 

Example: A new custom object record is created. The user creates a new note, which will trigger and send an email notification to a specified email. Since that was the first note added for that record, the subject line should say, "Update 1: A new note has been added to Custom Object Record. When another note is added, the subject like should say, "Update 2: A new note has been added to Custom Object Record". The number should increment for every new note added.

Any help one this would be great! Thanks!
trigger NoteAddedNotification on Note (after insert) 
{
    
    Set<ID> noteids = new Set<ID>();
    
    for (Note n:Trigger.new)
    {
        
        noteids.add(n.parentID);
    }
    
    List<Custom_Object__c> notelist = new List<Custom_Object__c>([SELECT Id, Name, MultiSelect_Picklist__c FROM Custom_Object__c WHERE ID in:noteids]);
    
     Messaging.SingleEmailMessage NoteToCS = new Messaging.SingleEmailMessage();
    
    	String[] toAddresses1 = new String[]
        {
        	'email1@test.com'
    	};
            
        String[] toAddresses2 = new String[]
        {
            'email2@test.com', 
        };    
        
        String[] toAddresses3 = new String[]{
        	'email3@test.com'    
        };
           
    for(Custom_Object__c c:notelist)
    {
    
        NoteToCS.setSubject('A note has been added to Custom Object: ' +c.Name);
        
        String stringURL  = URL.getSalesforceBaseUrl().toExternalForm()+ '/'+ c.Id;
        
        String body = 'A new note was added to ' + c.Name + '<br/>';
        body += 'Multi-Select Picklist: ' + c.MultiSelect_Picklist__c + '<br/>';
        body += 'Please click on the link to take a look:' + '<br/>';
        body += stringURL;
        
        
         if(String.isEmpty(c.MultiSelect_Picklist__c) && c.MultiSelect_Picklist__c == null)
         {
            
                c.addError('Please select a value for Multi-select Picklist before adding a 
                note.');

         }
        else
        {
               if(c.MultiSelect_Picklist__c.contains('Value1'))
               {
            		NoteToCS.setToAddresses(toAddresses1);
            		NoteToCS.setSaveAsActivity(false);
            		NoteToCS.setHtmlBody('<p style="font-family:Calibri;font-size:24px !important;">' + body + '</p>');
        	 		Messaging.sendEmail(new Messaging.Email[] {
             			NoteToCS
             		});
        		}
        		else if(c.MultiSelect_Picklist__c.contains('Value2'))
                {
            		NoteToCS.setToAddresses(toAddresses2);
            		NoteToCS.setSaveAsActivity(false);
            		NoteToCS.setHtmlBody('<p style="font-family:Calibri;font-size:24px !important;">' + body + '</p>');
        	 		Messaging.sendEmail(new Messaging.Email[] {
             			NoteToCS
             		});
        		}
        		else if(c.MultiSelect_Picklist__c.contains('Value3'))
                {
        			NoteToCS.setToAddresses(toAddresses3);
            		NoteToCS.setSaveAsActivity(false);
            		NoteToCS.setHtmlBody('<p style="font-family:Calibri;font-size:24px !important;">' + body + '</p>');
        	 		Messaging.sendEmail(new Messaging.Email[] {
             			NoteToCS
             		});	                             
        		}
        }
        
    }
update notelist ;
}
Hello,

We have a process which upon Opportunity creation, creates a record entry for a custom object which is linked via Lookup to the opportunity.
I now want to get the ID of the created lookup record and store it in a dedicated field on the opportunity. 
Any idea if I can achieve this with the standard feature of Process Builder or whether APEX is needed?
Many thanks! 
Hi there,

I want to make a trigger that fires when a custom field called "Behaviour Score" hits 100 and above. The trigger will change the current lead owner to a new lead owner that is a queue to be distributed between agents. Can anyone help me? 
my requirement:

Owner id should be changed on them when child of custom object are upserted. Owner Id on these should be updated with the owner id of account to which the upserting record belongs.

Please give me the solution it is very urgent to me. I hope you people will give me solution as soon as possible.
I am new to salesforce... please help... I have requirement like: one custom object Employee having three field Name,Account,Contact. Now I am creating a vf page with this three fields... but when I am saving my record from vf only employyee name is reflected. it is showing account and contact blank. And also i want to go redirect at record page which i am creating through vf when saved.
vf and controller as follows
vf 
<apex:page StandardController="EmployeeA__c" extensions="classes" >
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlock title="Employee Page">
                <apex:PageBlockSection >
                    <apex:inputText value="{!Name}"/>
                    <apex:inputField value="{!EmployeeA__c.Account__c}"/>
                    <apex:inputField value="{!EmployeeA__c.Contact__c}"/>
                </apex:PageBlockSection> 
                <apex:pageBlockSection >
                    <apex:commandButton value="Save" action="{!Save}"/>
                    <apex:commandButton value="Cancel" action="{!Cancel}"/>
                </apex:pageBlockSection>
            </apex:pageBlock>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller

public with sharing class classes {

    public String Name { get; set; }

    public  String Account {get; set;}
    
    public String Contact {get; set;}
    
   

     
      VAD03__EmployeeA__c objdlt;
     private ApexPages.StandardController controller;
    public classes(ApexPages.StandardController controller) {
    this.controller = controller;
    

    }

public PageReference save() {
        /*
        VAD03__EmployeeA__c objdlt = new VAD03__EmployeeA__c();
        objdlt.Name=Name;
        objdlt.VAD03__Account__c=Account;
        objdlt.VAD03__Contact__c=Contact;
        insert objdlt;
        */
        controller.cancel();   
        PageReference congratsPage = Page.Congratulations;
        congratsPage.setredirect(true);
        return congratsPage;
    }
    
        public PageReference Cancel() {
            
            controller.cancel(); // This takes care of the details for you.
            PageReference congratsPage = Page.Congratulations;
            congratsPage.setRedirect(true);
            return congratsPage;
}
}
 
Hi,

We are making a callout to external endpoint from Salesforce to get the attachments. when attachment size is more than 6 MB its throwing me Heap size limit error and we are running this callout from future method, where we are having this limit as 12 MB.

Please advise .... on any workarounds to overcome this ..
 
@future(callout=true)
    public static void SendAttachmentsToCase(Map<string,string> Initialres,ID CaseID,ID UserID,string UserName,string Password,string ticketNumber,string jobtime)
    {

                // Performs another callout to get appropriate attachment 
               List<attachment> FinalAttachmentList = new List<attachment>();
               for(string sg : Initialres.Keyset()) // Map of attachment Names and endpoint
               {
                Http h2 = new Http();
                HttpRequest req2 = new HttpRequest();
                Blob headerValue = Blob.valueOf(UserName+':'+Password);
                String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
                req2.setHeader('Authorization', authorizationHeader);
                req2.setHeader('Content-Type','application/json');
                req2.setEndpoint(Initialres.get(sg));
                req2.setMethod('GET');
                req2.setTimeout(60000);
                try
                {
                system.debug('heap size before req'+' '+ Limits.getHeapSize());
                HttpResponse res2 = h2.send(req2);
                system.debug('resposne'+ ' '+res2.getBody());
                                system.debug('heap size after req'+' '+ Limits.getHeapSize());

                blob image = res2.getBodyAsBlob(); 
                Attachment a = new Attachment (ParentId = CaseID,
                                           Body = image,
                                           OwnerId = UserID,
                                           CreatedById = UserID,
                                           Name = sg);
               FinalAttachmentList.add(a);
                }catch (Exception e)
                {
                    system.debug('exception message at 2nd callout level'+ ' '+ e.getMessage());
                 }
              }

              insert FinalAttachmentList;
    }

 
  • April 17, 2018
  • Like
  • 0
Hi All,

We have created a new User few days back. Now he is being notified of case assignment notification realted to a Queue and to which he doesn't belongs but he is a manager of queue member for that queue. Not sure how he is being notified.

I have reviewed all the workflow and process builder emails alert notification, but didn't find any tracess for this users.

Can someone please let me know, how can we exclude notifications for this users from the Queue.
 
  • November 28, 2017
  • Like
  • 0
We have a requirement that when a customer logs in to customer portal and when they click on the link they should be logged in to 3rd party application automatically with same portal credentials and redirect to a page on 3rd part application.
I was able to get this working from salesforce using connected app but how can we do the same for customer portal.
Please share some thoughts on this...!!!
  • July 13, 2017
  • Like
  • 0
Hi ,

We have a public page embeded with VF page that captures the Customer portal user ID and password to login to customer portal. Now we would like to have these users automatically logged in to Zendesk once they login to customer portal from public web site. I am not sure of how to login to Zendesk via API.

Any thoughts on this would be highly appreciated .....!!!!!
  • July 07, 2017
  • Like
  • 0
Hi,

Could someone please provide any suggestions to acheive the load balancing of cases being assigned to set of users in round robin manner. I have installed the Round robin record assignment (unmanaged) app exchange application. I have modified the code to work for logged in users only and now I need to perform load balancing among the logged in users.

Any thoughts would be helpful...!!!
  • January 30, 2017
  • Like
  • 0
Hi All,

I have installed a round robin record assignment (Un managed package) application from app exchange and now I woud like to modify the code to have this work only for logged in users in salesforce, I have tried retrieving the session info from "Authsession" object but I could see a multiple sessions opened for a user and I am not sure whether a user is currently logged in or not and our ORG has a session time out set to 12 hours.

Any thoughts would be really appreciated...!!!!
Thanks in advance ..!!!
  • January 25, 2017
  • Like
  • 0
Hi All,

I have a requirement to bring up the same look and feel for a custom look-up field (Faculity) (lookup to user object) similar to record owner change. I mean, we would like to have a similar page opened like record owner change, when a user clicks on the Faculity custom look-up field instead of standard user look-up page. Also the Send notificaion email button should send an email to faculity if its marked true.

record owner change​ page 
User-added image
We would like to have above page opened, when an user clicks on the Faculity look-up field .
User-added image

Any thoughts would be highly appreciated...!!!

Thanks in advance ...!!!
  • November 04, 2016
  • Like
  • 0
Hi,

Can someone please let me know, Can we override the standard save and close button on case edit page or remove from page layout 
  • August 30, 2016
  • Like
  • 0
Hi,

I have a test class, which seems to be passed when run through the developer console but when I run through the apex test execution it fails 

Any thoughts would be appreciiated 

Thanks..!!!
  • August 25, 2016
  • Like
  • 0
HI,
I have a class the returns the set of records based on createddate. So how to write a test class and test the results of that class ..
In a test class, If I instantiate a class and call the method then it covers me 100%. But when I try to verify the results it doesn't return me any records.

Also I have gone through some blog and got that we can provide values to created date on test class using test.setcreateddate(recordid,datetime)

Can someone please help me ...!!!
 
public with sharing class UnclaimCases
{
    public list<case> caseami {get;set;}
    public string strhours = Label.DateFilter; // custom label stores values in hours 
    public integer hours = integer.valueof(strhours);
    Datetime currenttime = system.now();
    datetime  acttime  = currenttime.addhours(-hours);
    public final static Id custid = Schema.SObjectType.case.getRecordTypeInfosByName().get('Support').getRecordTypeId();   

    public UnclaimCases()
    {

     caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND Createddate>: acttime  AND Createddate< : currenttime  ORDER BY Priority  LIMIT 10000 ];
    }

    public pagereference inc()
     {
         Datetime currenttimeami = system.now();
         datetime  acttimeami  = currenttime.addhours(-hours);
         caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND Createddate>: acttimeami  AND Createddate<: currenttimeami ORDER BY Priority LIMIT 10000 ];

         system.debug('caseami' + caseami );
         system.debug(' current datetime value ' + currenttimeami );
         system.debug(' act datetime value ' + acttimeami );
        return null;
    }


}
Test class 
@isTest
public class TestUnclaimCases 
{

    @isTest static void Unclamethod()
        {

            Id queueId =[select Id from Group where Name = 'T Queue' and Type = 'Queue'].Id;

            Id custid = Schema.SObjectType.case.getRecordTypeInfosByName().get('Support').getRecordTypeId(); 

            case c1 = new case(RecordTypeId = custid, Status = 'Unclaimed', Product_Type__c = 'A',Priority = 'SEV 1' , ownerid=queueId);
              insert c1;
    datetime delay1 = datetime.now.addhours(-2);
          Test.setcreateddate(c1,delay1);
            case c2 = new case(RecordTypeId = custid, Status = 'Rep On Site', Product_Type__c = 'A',Priority = 'SEV 2' , ownerid=queueId);
           insert c2;
  datetime delay2 = datetime.now.addhours(-2);
          Test.setcreateddate(c2,delay2);
            case c3 = new case(RecordTypeId = custid, Status = 'Escalated', Product_Type__c = 'A',Priority = 'SEV 2' );
            insert c3;
          datetime delay3 = datetime.now.addhours(-2);
          Test.setcreateddate(c3,delay3);

            UnclaimCases uc = new UnclaimCases();
            uc.inc();
            //list<case> fuc.caseami;
            system.assertEquals(2,uc.caseami.size());


        }
    }

 
  • August 24, 2016
  • Like
  • 0
Hi,

I have a class the returns the set of records based on lastmodified date. So how to write a test class and test the results of that class ..

In a test class, If I instantiate a class and call the method then it covers me 100%. Not sure how to verify the results 

In the below class I am using custom labels to store the number of hours 
Apex class
 
public with sharing class UnclaimCases
{
    public list<case> caseami {get;set;}
    public string strhours = Label.DateFilter;
    public integer hours = integer.valueof(strhours);
    Datetime currenttime = system.now();
    datetime  acttime  = currenttime.addhours(-hours);
    public final static Id custid = Schema.SObjectType.case.getRecordTypeInfosByName().get('Support').getRecordTypeId();   
    
    public UnclaimedAMICases()
    {
     
     caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND LastModifiedDate >: acttime  AND LastModifiedDate < : currenttime  ORDER BY Priority  LIMIT 10000 ];
    }
    
    public pagereference inc()
     {
         Datetime currenttimeami = system.now();
         datetime  acttimeami  = currenttime.addhours(-hours);
         caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND LastModifiedDate >: acttimeami  AND LastModifiedDate <: currenttimeami ORDER BY Priority LIMIT 10000 ];
         system.debug('caseami' + caseami );
         system.debug(' current datetime value ' + currenttimeami );
         system.debug(' act datetime value ' + acttimeami );
        return null;
    }
    

}

 
  • August 19, 2016
  • Like
  • 0
Hi,

I am having issue with group of users. when they create a new case they are being redirected to knowledge articles, but they dont have knowledge user licence.

Any thoughts would be highly appreciated...!!!
  • August 17, 2016
  • Like
  • 0
Hi,

Can someone please help me in covering the test class for the below code and I have tried a lot to cover it to 100% but I am getting 81% 

public with sharing class COCaseComment
{
    public String test2 {get;set;}
    public String test1 {get;set;}
    public string status {get;set;}

    public void save() {
        Id caseId = ApexPages.currentPage().getParameters().get('caseid');
        SavePoint sp = Database.setSavePoint();
        status = 'unsaved';
        try {
            Case c = [SELECT Id,status,xyz1__c, xyz2__c FROM Case WHERE Id = :caseId FOR UPDATE];
            c.Status = 'Closed';
            insert new casecomment(ParentId = caseId, commentbody = 'Question:'+ '\n' + test1 + '\n' + 'solution :'+ '\n'+ test2 , IsPublished = true);
            update c;
            status = 'saved';
        } catch(Exception e) {
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, e.getMessage()));
            Database.rollback(sp);
        }
    }
}

Test class 

@isTest
public class TestCustomerOperationsCaseComment
{
    @isTest public static void withcaseid() {
        case c = new
        case (status = 'New', Origin = 'Phone', xyz1__c= 'AMR', xyz2__c = 'Charting Issues');
        insert c;
        case ca = [select id, status, xyz1__c ,xyz2__c from case where status = 'New'];
        Test.setCurrentPage(page.COcaseComment);
        COCaseComment cs = new COCaseComment();
        cs.Test1 = ('test1');
        cs.Test2 = ('test2');
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        if (ca.id != null) {
            cs.save();
        }
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = 'Question:'+ '\n' + test1 + '\n' + 'solution:'+ '\n'+ test2 ;
        system.assertEquals(str, cm.CommentBody);
        system.assert(true, cm.ispublished);
        case g = [select Status from case where ID = :ca.Id ];
        system.assertEquals('Closed', g.status);
    }


    @isTest static void caseWithoutproduct() 
   {
      
            case c = new
            case (status = 'New', Origin = 'Phone', xyz2__c = 'Charting Issues');
            insert c;
            pagereference pr = page.COcaseComment;
            pr.getParameters().put('caseid', c.Id);
            test.setCurrentPage(pr);
            COCaseComment cc = new COCaseComment();
            cc.save();
          System.assert(ApexPages.hasMessages(ApexPages.SEVERITY.Error));
         System.assertEquals('unsaved', cc.status);
    
    }
}



 
  • July 28, 2016
  • Like
  • 1
Hi,

I have a soql query where I am using custom labels to specify the date range in string example : THIS_WEEK or something else in future and binding it to the lastmodified date time. when I bind it throws me the below error any thoughts would be appreciated.
In apex

soql query :
  Select status ,CaseNumber,Priority from case where LastModifiedDate =:Label.Thisweek (Thisweek contains a value : THIS_WEEK)

error : Invalid bind expression type of String for column of type Datetime 
 
  • July 22, 2016
  • Like
  • 0
Hi,

I have a requirement to build a bar chart with
1. x-axis labelled "Cases grouped by week"contains the case last modified date grouped by each week (Starting from saturday - friday) from last 6 Months and data need to be grouped by case product type "X" and "Y".
2. Y -axis with % of records passed by case products "X" and "Y"  (I have another custom fields on case records named pass/fail it is a formula field and it will output pass or fail .So based on this I need to calculate the % of records passed only) .

Could someone please suggest me that can we acheive the above scenario using VF charting ??

In the standard report builder I am able to acheive the above except the case last modified date grouped by week starting from Saturday to Friday (In standard grouping of calender week I can see week starting from Sunday - Saturday i.e 7/3/2016 to 7/9/2016 ). But i need week starting from Saturday to Friday as 7/2/2016 to 7/8/2016 , 7/9/2016 to 7/15/2016.

 
  • July 06, 2016
  • Like
  • 0
Hi,

I have written a test class that covers 86% leaving out the apexpages.addmessage () in catch block, but majorly it throws the validation exceptions on that object when I try to update a record.(Here I am updating case status to closed and I have some custom fields to be filled out while closing the case).

My test class has 2 methods. 1st method is having the case with all the fields filled this covers all the code except catch block and 2nd method without the required fields while closing the case and even though it doesn't cover my test class to full 100% 

Can someone please provide any suggestions .

In my case I am updating the case status to closed and while closing the case I have 2 custom fields that should not be "null" 1. xyz1__c and 2.xyz2__c (Their are validation rules written on the case obejct and therse throwing me the exceptions if these fields are null while updating the case) I am not sure how to cover the validation exception in catch black in Test class 


Apex controller 
public with sharing class OCaseComment
{
    public String test2 { get; set; }
    public String test1 { get; set; }
    public string status {get;set;}
    public casecomment ca;
    public case c ;
    public ID caseId ;
    
    public pagereference save() 
    {
        
        caseId = ApexPages.currentPage().getParameters().get('caseid');
        system.debug('case id entered' + caseId);
        ca = new casecomment();
        ca.ParentId= caseId;
        ca.commentbody = 'question:'+ test1 + '\n' + 'solution:'+ test2 ;
        ca.IsPublished = true;
        list<case> c = [select Status, xyz1__c, xyz2__c from case where ID=:caseId];
        list<case> cg = new list<case>();
        for(case cd : c)
        {
            cd.Status = 'Closed';
            cg.add(cd);   
        }
       
        try{   
             if(cg.size() > 0 && cg[0].xyz1__c!= null && cg[0].xyz2__c !=null)
        {
            insert ca;
        }
            update cg;
            status = 'saved'; 
            system.debug('status value'+ status);
           
        }catch(DmlException d)
        {
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;  
            status = 'unsaved';
        }
        return null;
    }
    
    
}

Test class 

@isTest
public class TestClassOCaseComment
{
    @isTest public static void withcaseid()
    {
        
            case c = new case(status = 'New',Origin = 'Phone',xyz1__c= 'Stats',xyz2__c= 'Issues');
            insert c;
            case ca = [select id, status,xyz2__c from case where status = 'New'];
            Test.setCurrentPage(page.SCaseComments);
            OCaseComment cs = new OCaseComment();
            cs.Test1=('test1');
            cs.Test2=('test2');
            apexpages.currentPage().getparameters().put('caseid', ca.id);
            if(ca.id != null)
               {
                 cs.save();
               }
       
            casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
            string str = 'Question:'+ cs.test1 +'\n'+ 'Solution:'+ cs.test2 ;
            system.assertEquals(str , cm.CommentBody);
            system.assert(true, cm.ispublished);
            case g = [select Status from case where ID =: ca.Id];
            system.assertEquals('Closed', g.status);
     
     }
    
    @isTest static void caseWithoutproduct()
    {
        try{
            case c = new case(status = 'New',Origin = 'Phone', xyz2__c= 'Issues');
        insert c;
        pagereference pr = page.SCaseComments;
        pr.getParameters().put('caseid',c.Id);
        test.setCurrentPage(pr);
       OCaseComment cc = new OCaseComment();        
            cc.save();  
        }catch (Exception e){     
              System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
            System.Assert(e.getMessage().contains('xyz1__c'));
                               }
}
}
  • June 22, 2016
  • Like
  • 0
Hi,

I have written a test class that covers 86% leaving out the apexpages.addmessage () in catch block, but majorly it throws the validation exceptions on that object when I try to update a record.(Here I am updating case status to closed and I have some custom fields to be filled out while closing the case).

My test class has 2 methods. 1st method is having the case with all the fields filled this covers all the code except catch block and 2nd method without the required fields while closing the case and even though it doesn't cover my test class to full 100% 

Can someone please provide any suggestions .


 
  • June 20, 2016
  • Like
  • 0
Hi,

I have a requirement to put a case record link in email template. so that it can be accessed by the customer portal users.

I have tried appending the record id to my customer portal url, but it throws me an error.

Any thoughts would be appreciated.
  • June 16, 2016
  • Like
  • 0
Hi ,

Can someone please help me to cover the below 2 lines in catch block in my contoller class 

  Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
I have used the below code in my class but its entering the catch block while testing, but not sure how to cover those lines.
if(Test.isRunningTest())
              integer intt = 10/0;

Apex class 

public with sharing class mycasecom {

    public String test2 { get; set; }
    public String test1 { get; set; }
    public string test3 {get;set;}
    public string status {get;set;}
    public casecomment ca;
    public case c ;
    public ID ID ;
       
     public void save() 
     {
     
     id = ApexPages.currentPage().getParameters().get('caseid');
     system.debug('case id entered' + ID);
      ca = new casecomment();
      ca.ParentId= id;
      ca.commentbody = test1 + '\n' + test2 + '\n' + test3;
      ca.IsPublished = true;
      list<case> c = [select Status from case where ID=:ID];
      list<case> cc = new list<case>();
      for(case cd : c)
      {
          cd.Status = 'Closed';
          cc.add(cd);
      }
      try {
             insert ca;
              update cc;
           status = 'saved';
         system.debug('status value'+ status);
       
          if(Test.isRunningTest())
              integer intt = 10/0;
       }catch(DmlException d)
      {
       Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
      }

}
}

Test Class 

@isTest
public class PopupTestClass 
{
    @isTest public static void withcaseid()
    {
        
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        case ca = [select id, status from case where status = 'New'];
        pagereference p = page.casecomment;
        test.setCurrentPage(p);
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
   
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        cs.save();
        
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = cs.test1 +'\n'+ cs.test2 +'\n' +cs.test3;
        system.assertEquals(str , cm.CommentBody);
        system.assert(true, cm.ispublished);
        case g = [select Status from case where ID =: ca.Id];
        system.assertEquals('Closed', g.status);
        
        
            }
    
    @isTest static void withoutcaseid()
    {
        
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        pagereference p = page.casecomment;
        test.setCurrentPage(p);
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
       
        apexpages.currentPage().getparameters().put('caseid', null);
        cs.save();
       
        system.assertEquals('unsaved', cs.status);
        
   }
}
  • June 15, 2016
  • Like
  • 0
Hi ,

I have a requirement where I need to display a vf page as pop -up  on button click on case and the vf page would include some text questions and once these are answered and user clicks on save button , then these text values should be inserted as a new comment to that particular case.

I have started working on this but when I create a new case comment by supplying required fields Parentid and commentbody. It throws me an error : Parentid doesn't exist or some time commentbody doesn't exists.

Can someone please help me....


Error: test Compile Error: Variable does not exist: CommentBody at line 13 column 8

public with sharing class test 
{
    public string text {get;set;}
    private CaseComment c ;
    
    public test ()
    {
        c = new CaseComment ();
    }
   public PageReference save() 
   {
       c = new CaseComment();
       c.CommentBody = text ;   ***** error *********
       c.ParentId = '5009000000dza7i';
       insert c ;
        
        return null;
   }

    
    
    
}
 
  • June 10, 2016
  • Like
  • 0
Hi,

Can someone please help me in covering the test class for the below code and I have tried a lot to cover it to 100% but I am getting 81% 

public with sharing class COCaseComment
{
    public String test2 {get;set;}
    public String test1 {get;set;}
    public string status {get;set;}

    public void save() {
        Id caseId = ApexPages.currentPage().getParameters().get('caseid');
        SavePoint sp = Database.setSavePoint();
        status = 'unsaved';
        try {
            Case c = [SELECT Id,status,xyz1__c, xyz2__c FROM Case WHERE Id = :caseId FOR UPDATE];
            c.Status = 'Closed';
            insert new casecomment(ParentId = caseId, commentbody = 'Question:'+ '\n' + test1 + '\n' + 'solution :'+ '\n'+ test2 , IsPublished = true);
            update c;
            status = 'saved';
        } catch(Exception e) {
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, e.getMessage()));
            Database.rollback(sp);
        }
    }
}

Test class 

@isTest
public class TestCustomerOperationsCaseComment
{
    @isTest public static void withcaseid() {
        case c = new
        case (status = 'New', Origin = 'Phone', xyz1__c= 'AMR', xyz2__c = 'Charting Issues');
        insert c;
        case ca = [select id, status, xyz1__c ,xyz2__c from case where status = 'New'];
        Test.setCurrentPage(page.COcaseComment);
        COCaseComment cs = new COCaseComment();
        cs.Test1 = ('test1');
        cs.Test2 = ('test2');
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        if (ca.id != null) {
            cs.save();
        }
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = 'Question:'+ '\n' + test1 + '\n' + 'solution:'+ '\n'+ test2 ;
        system.assertEquals(str, cm.CommentBody);
        system.assert(true, cm.ispublished);
        case g = [select Status from case where ID = :ca.Id ];
        system.assertEquals('Closed', g.status);
    }


    @isTest static void caseWithoutproduct() 
   {
      
            case c = new
            case (status = 'New', Origin = 'Phone', xyz2__c = 'Charting Issues');
            insert c;
            pagereference pr = page.COcaseComment;
            pr.getParameters().put('caseid', c.Id);
            test.setCurrentPage(pr);
            COCaseComment cc = new COCaseComment();
            cc.save();
          System.assert(ApexPages.hasMessages(ApexPages.SEVERITY.Error));
         System.assertEquals('unsaved', cc.status);
    
    }
}



 
  • July 28, 2016
  • Like
  • 1
I'm hoping you clever people are able to help me please, as I do not know how to write Apex Code.

I have pulled the below from another post (which works), but need to adopt it for the following circumstances, and wondered whether someone might be able to help please:
  • For any update made, update field 'Last_Chatter_Feed_Timestamp__c' with todays date.
  • For any update made and the profile ID = ABC, flip the status to 'Open'

trigger FeedThis on FeedComment(after insert, after update){

    List<Case> updates = new List<case>();
    List<id> userList = new List<ID>();
    List<Id> feedItemList = new List<id>();
    for(FeedComment fc: trigger.new){
        feedItemList.add(fc.FeedItemId);
        userList.add(fc.InsertedById);
    }
    Map<Id, FeedItem> feedMap = new Map<id, FeedItem>([select id,InsertedById,Visibility from feedItem where Id IN :feedItemList]);
    Map<Id, User> userMap = new Map<Id, User>([select id, usertype, name from user where ID IN :userList]);
    for(FeedComment fc: trigger.new){
        if (feedMap != null && feedMap.containsKey(fc.feedItemId) && fc.ParentId.getSObjectType() == Case.SObjectType) {
            updates.add(new Case(
                    Id = fc.ParentId,
                    Status = 'Open'
                    ));
        }
        
    }
    if(updates != null && updates.size() > 0)
    update updates;
}

Many Thanks In Advance

Im sending an email with an attactment and i got this error.

does anyone have an idea on this error?

System.EmailException: SendEmail failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, null argument for JSONGenerator.writeBooleanField(): []

 

Hello there,
Please help me to fix this error. My records not updating.

Apex script unhandled exception by user/organization: 0051X0000018hKG/00D1X0000008akn
Source organization: 00Db0000000HO6N (null)
Failed to process batch for class 'AllTimeRevenueAndYtDRevenueBatch' for job id '7071X00000FepEJ'

caused by: System.LimitException: Too many query rows: 50001

Class.AllTimeRevenueAndYtDRevenueBatch.execute: line 23, column 1
global class AllTimeRevenueAndYtDRevenueBatch implements Database.Batchable<sObject>,Database.Stateful,Schedulable {
global Decimal sum;
    public list<Account> oldInvoicesToUpdate = new list<Account>();
    public list<Account> invToUpdate = new list<Account>();
    public Set<ID> newEntitiesIds = new Set<ID>();
    global AllTimeRevenueAndYtDRevenueBatch(){}
        /* Batch class constructor */
    //Start method
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        //String query='SELECT id, Amount from Opportunity';
         String query='SELECT id, Normalized_Amount__c,Account__c from Invoice__c';
         return Database.getQueryLocator(query);
        }

    //Excute method
    
global void execute(Database.BatchableContext BC, List<Invoice__c> scope)
{
    //Excution logic
    //List<Opportunity> opp= new List<Opportunities>();
    //AggregateResult[] gr= [SELECT SUM(Amount) optyamt FROM Opportunity];
    AggregateResult[] gr= [SELECT SUM(Normalized_Amount__c) NormalizeAmount,Grouping(Account__c), Account__c
                                 FROM Invoice__c
                                 WHERE Category_Invoice__c != 'Monthly' AND Status__c != 'invoice_canceled' 
                                 GROUP BY Account__c];
    
    for(AggregateResult ag:gr){
          if((ID)ag.get('Account__c') != null){
                                         invToUpdate.add(new Account (
                                             ID = (ID)ag.get('Account__c'),
                                             //YtD_Revenue_for_Kantox__c = (Double)ag.get('NormalizeAmount'),
                                             AllTimeRevenueKantox__c = (Double)ag.get('NormalizeAmount')
                                             
                                         ));
                                     }
        
        //sum = (Decimal)ag.get('optyamt');
         
    }
    try{
            if(!invToUpdate.isEmpty()){
                update invToUpdate;
            }
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    
}
      global void finish(Database.BatchableContext BC){
            // Finish logic
          system.debug(''+sum); 
       }
    public void execute(SchedulableContext Sc) {
        AllTimeRevenueAndYtDRevenueBatch batch = new AllTimeRevenueAndYtDRevenueBatch();
        Database.executeBatch(batch);    
    }
}

 
I'm very new to Saleforce development and have a problem with code coverage.  I'm using a switch case but can't get code coverage for the result variables.

Class:
public with sharing class cBannerManagedByReseller
{

    Public list<Banner_Managed_By_Reseller__c> lstPB = new list<Banner_Managed_By_Reseller__c>();
    Public list<Merchant_Risk_Summary__c> lstRisk = new list<Merchant_Risk_Summary__c>();
    Public List<Account> acct;  
    Public string acctID;
    Public string StatusBGColor{get;set;}
    Public string StatFontColor {get;set;}
    Public string AcctRankingBGColor{get;set;}
    Public string ARFontColor {get;set;}
    Public string qryStatus {get;set;}
    Public string qryAcctRanking {get;set;}
     
    public Id accountId {get; set;}

    public cBannerManagedByReseller(ApexPages.StandardController stdController) 
    {
        this.accountId= stdController.getId();
    }
 
    public List<Account> getAcct() 
    {
        list<Account> acct = [Select Id, Name, Organization__c, Industry, Organization__r.Partnership_Type__c, Phone, Account_Ranking__c, CardConex_Status__c FROM Account WHERE Id =:accountId limit 1];
        
        for (Account accts: acct)
        {
           qryStatus = accts.CardConex_Status__c;
           qryAcctRanking = accts.Account_Ranking__c;
        }    
            switch on (qryStatus) 
            {
                when 'Risk - Funds on hold', 'Risk - Sent to Collections', 'Risk - Levy Hold', 'Risk - Reserve', 'NA - *NOT OWNED BY BLUEFIN*', 'ACH Reject', 'Approved on hold per Underwriting', 'Capped Account'
                {      
                    StatusBGColor = 'Yellow';
                    StatFontColor = 'Red';  
                }  
                
                When 'Declined', 'Declined for Fraud'    
                {
                    StatusBGColor = 'Gray';
                    StatFontColor = 'White';
                }            

                when 'Withdrawn'
                {       
                    StatusBGColor= 'Blue';
                    StatFontColor = 'White';  
                }
                
                when 'Active'
                {       
                    StatusBGColor= '#ADD8E6';  //Light Blue
                }

                when 'SMAP Account'
                {       
                    StatusBGColor= '#FF1493';  //Deep Pink
                    StatFontColor = 'White';
                }

                when 'Headquarters situation - multiple accounts tied together'
                {
                    StatusBGColor = '#8A2BE2';
                    StatFontColor = 'White';            
                }
                
                when 'Bora Payments Account'
                {
                    StatusBGColor = '#ADFF2F';
                } 
                           
                when 'Mindbody-Supported Account'
                {
                    StatusBGColor = 'Orange';
                }

                when 'Bankruptcy'
                {
                    StatusBGColor = 'Black';
                    StatFontColor = 'White'; 
                }

                when 'Closed', 'Seasonal Close', 'Seasonal Merchant'  
                {       
                    StatusBGColor= 'Red';  //Tannish Orange
                }
                
                when 'Approved on ACH Delay' 
                {       
                    StatusBGColor= 'Olive';  
                    StatFontColor = 'White';
                }

                when 'P2PE Merchant' 
                {       
                    StatusBGColor= '#20B2AA';  //Light Seagreen (Turquiose)
                }


                when 'Decryptx Merchant' 
                {       
                    StatusBGColor= '#4B0082';  //Indigo Dark Purple)
                }

                when 'Live Test Account'
                {       
                    StatusBGColor= '#ADFF2F';   //Bright Bright Green
                }
                
                when 'Sales Order Account Page'
                {       
                    StatusBGColor= '#ADFF2F';   //Purple
                    StatFontColor = 'White';
                }            

                when else 
                {       
                    StatusBGColor= 'Blue';  
                    StatFontColor = 'White';
                } 
        
            }
               
            switch on (qryAcctRanking) 
            {
                when 'VIP', 'Tier II - High Processing Merchant', 'Tier III - High Processing Merchant'
                {      
                    AcctRankingBGColor= 'LightGreen';  //Light Green
                    ARFontColor = 'Black';  
                }  
                 
                when 'Tulsa TOP 100', 'Managed By Nathan Steinmetz', 'Managed by Linda Chastain'
                {       
                    AcctRankingBGColor= 'blue';
                }
               
                when 'Gateway Only' 
                {       
                    AcctRankingBGColor = 'DeepSkyBlue';     //Bright Blue
                }
                
                when else 
                {       
                    AcctRankingBGColor = 'Blue';  
                    ARFontColor = 'White';
                }  
            }
        return acct;
    }

    public List<Banner_Managed_By_Reseller__c> getlstPB() 
    {
        list<Banner_Managed_By_Reseller__c> lstPB = [SELECT Id, Name, Account_ID__c, Contact_Email__c, Contact_Phone__c, Background_Color__c, Font_Color__c, Message__c FROM Banner_Managed_By_Reseller__c WHERE Account_ID__c=:accountId limit 1];
        return lstPB;
    }
  
    public List<Merchant_Risk_Summary__c> getlstRisk() 
    {
        list<Merchant_Risk_Summary__c> lstRisk = [SELECT Id, Name, Account__c, Rules_Triggered__c FROM Merchant_Risk_Summary__c WHERE Account__c=:accountId limit 1];
        return lstRisk;
        
    } 
  
}


Test Class:
@isTest
public class cBannerManagedByResellerTest 
{
       
    static testmethod void MyTest()
    {        
       cBannerManagedByResellerTest banner = new cBannerManagedByResellerTest();
        Account a = new Account();
        a.name='Test Company1';
        a.CardConex_Status__c='Active';
        a.Account_Ranking__c='VIP';
        insert a;
        //return acct; 
        //Add the organization
        Banner_Managed_By_Reseller__c b = new Banner_Managed_By_Reseller__c();
        b.Account_ID__c = a.Id;
        b.Background_Color__c='Blue';
        b.Font_Color__c='White';
        b.Contact_Email__c = 'anyname@gmail.com';
        b.Contact_Phone__c = '1234567890';
        insert b;
        System.assert(b != null);

        //The the Merchant Risk object  
        Merchant_Risk_Summary__c r = new Merchant_Risk_Summary__c();
        r.account__c = a.ID;
        r.Comment__c = 'This is a test';
        r.Risk_Profile__c = 'a0SU00000003WxfMAE';
        insert r;
        system.assert(r !=null);
        
        PageReference pageRef = Page.BannerManagedByReseller;
        pageRef.getparameters().put('Account_ID__c', a.id);  
        Test.setCurrentPage(pageRef);
        Apexpages.StandardController sc = new Apexpages.StandardController(b);

        cBannerManagedByReseller ext = new  cBannerManagedByReseller(sc);         
        List<Banner_Managed_By_Reseller__c> lstB = ext.getlstPB();
        List<Account> lstA = ext.getAcct();
        List<Merchant_Risk_Summary__c> lstM = ext.getlstRisk();
        System.assert(ext.lstPB  != null);
        
        list<Account> acct = [Select Id, Name, Organization__c, Industry, Organization__r.Partnership_Type__c, Phone, Account_Ranking__c, CardConex_Status__c FROM Account];

        for (Account accts: acct)
        {
            string qryStatus = null;
             string qryAcctRanking = null;
            string ABFontColor = null;
            string AcctRankingBGColor = null;
            string StatusBGColor = null;
            string StatFontColor = null;

            system.assertEquals(null, qryStatus);
            system.assertEquals(null, qryAcctRanking);
            system.assertEquals(null, ABFontColor);
            system.assertEquals(null, AcctRankingBGColor);
            system.assertEquals(null, StatusBGColor);
            system.assertEquals(null, StatFontColor);
            
            qryStatus = 'Active';
            qryAcctRanking = 'VIP';
        }    
        
            string qryStatus = 'Active';
             string qryAcctRanking = 'VIP';
            string ABFontColor = null;
            string AcctRankingBGColor = null;
            string StatusBGColor = null;
            string StatFontColor = null;

            system.assertEquals('Active', qryStatus);
            system.assertEquals('VIP', qryAcctRanking);
            system.assertEquals(null, ABFontColor);
            system.assertEquals(null, AcctRankingBGColor);
            system.assertEquals(null, StatusBGColor);
            system.assertEquals(null, StatFontColor);
    
        switch on (qryStatus) 
         {
                when 'Risk - Funds on hold', 'Risk - Sent to Collections', 'Risk - Levy Hold', 'Risk - Reserve', 'NA - *NOT OWNED BY BLUEFIN*', 'ACH Reject', 'Approved on hold per Underwriting', 'Capped Account'
                {      
                    StatusBGColor = 'Yellow';
                    StatFontColor = 'Red';  
                }  
                
                When 'Declined', 'Declined for Fraud'    
                {
                    StatusBGColor = 'Gray';
                    StatFontColor = 'White';
                }            

                when 'Withdrawn'
                {       
                    StatusBGColor= 'Blue';
                    StatFontColor = 'White';  
                }
                
                when 'Active'
                {       
                    StatusBGColor= '#ADD8E6';  //Light Blue
                }

                when 'SMAP Account'
                {       
                    StatusBGColor= '#FF1493';  //Deep Pink
                    StatFontColor = 'White';
                }

                when 'Headquarters situation - multiple accounts tied together'
                {
                    StatusBGColor = '#8A2BE2';
                    StatFontColor = 'White';            
                }
                
                when 'Bora Payments Account'
                {
                    StatusBGColor = '#ADFF2F';
                } 
                           
                when 'Mindbody-Supported Account'
                {
                    StatusBGColor = 'Orange';
                }

                when 'Bankruptcy'
                {
                    StatusBGColor = 'Black';
                    StatFontColor = 'White'; 
                }

                when 'Closed', 'Seasonal Close', 'Seasonal Merchant'  
                {       
                    StatusBGColor= 'Red';  //Tannish Orange
                }
                
                when 'Approved on ACH Delay' 
                {       
                    StatusBGColor= 'Olive';  
                    StatFontColor = 'White';
                }

                when 'P2PE Merchant' 
                {       
                    StatusBGColor= '#20B2AA';  //Light Seagreen (Turquiose)
                }


                when 'Decryptx Merchant' 
                {       
                    StatusBGColor= '#4B0082';  //Indigo Dark Purple)
                }

                when 'Live Test Account'
                {       
                    StatusBGColor= '#ADFF2F';   //Bright Bright Green
                }
                
                when 'Sales Order Account Page'
                {       
                    StatusBGColor= '#ADFF2F';   //Purple
                    StatFontColor = 'White';
                }            

                when else 
                {       
                    StatusBGColor= 'Blue';  
                    StatFontColor = 'White';
                } 
        
            }
               
            switch on (qryAcctRanking) 
            {
                when 'VIP', 'Tier II - High Processing Merchant', 'Tier III - High Processing Merchant'
                {      
                    AcctrankingBGColor= 'LightGreen';  //Light Green
                    ABFontColor = 'Black';  
                }  
                 
                when 'Tulsa TOP 100', 'Managed By Nathan Steinmetz', 'Managed by Linda Chastain'
                {       
                    AcctRankingBGColor= 'blue';
                }
               
                when 'Gateway Only' 
                {       
                    AcctRankingBGColor = 'DeepSkyBlue';     //Bright Blue
                }
                
                when else 
                {       
                    AcctRankingBGColor = 'Blue';  
                    ABFontColor = 'White';
                }            
            }
        System.AssertEquals(true, AcctRankingBGColor !=Null);
        System.AssertEquals(true, ABFontColor !=Null);
        

    }
}
I have created two sandboxes at a time in free 30 days trail edition. But even though I successfully created I cannot login to sandboxes   by username  suffixed with '.Sandbox name' and used production password. 
Hi , Iam writing belowtest class . But Iam getting below error.

"System.QueryException: List has no rows for assignment to SObject ".


@isTest 
private class SMXNPXSurveyBLTest {     

static testMethod void testNPXsurveycasecreation(){   
  
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
       // Insert account as current user
        
            Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
            UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
          user u = new User(alias = 'jsmith', email='jsmith@acme.com', 
                emailencodingkey='UTF-8', lastname='Smith', 
                languagelocalekey='en_US', 
                localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
                timezonesidkey='America/Los_Angeles', 
                username='jsmith@acme.com');
                
                System.RunAs(thisUser){
            insert u;
            
       
      Account a = new Account(Name='SMX Test Account', Industry='Test Industry',BillingPostalCode='211212',BillingStreet='TestStreet',BillingCity='TestCity',BillingCountry='Japan');
      insert a;
        
     Contact c = new Contact(FirstName='SMX TestFName1', LastName='SMX TestLName1', AccountID=a.id, Email='this.is.a.smx.test@acmedemo.com', Phone='9999999');
     insert c;  
        
  
 Workgroup__c wg=New Workgroup__c();
 wg.Name='test';
 insert wg;
 
 
 Workgroup_User_Role__c WUR = new Workgroup_User_Role__c();
 WUR.Workgroup__c=wg.Id;
 WUR.Case_type__c='Admin SR';
 WUR.Product_Series__c='PULSE ONE';
 WUR.Role_Name__c=r.id;
 insert WUR;
 

 case ca= new case();
 ca.Accountid=a.id;
 ca.contactid=c.id;
 ca.subject='testsubject';
 ca.Description='testdescription';
 ca.status='submitted';
 ca.Priority='High';
 ca.Severity__c='test';
 ca.origin='Email';
 ca.Transaction_Type__c='Admin SR';
 ca.Product_Series__c='PULSE ONE';
 ca.Platform__c='PUSE ONE CONSOLE';
 ca.Release__c ='2.0';
 ca.Category__c='AAA';
 ca.SR_Category1__c='Question';
 ca.SR_Category2__c='Other';
 Test.starttest();
 insert ca;
 Test.stoptest();

 
NPX_Survey_Record__c npx = new NPX_Survey_Record__c();
npx.Account__c=a.id;
npx.contact__c=c.id;
npx.case__c=ca.id;
npx.name='test';
npx.Primary_Score__c=10;
npx.primary_comment__c='test comment';
npx.Survey_ID__c='PULSESECURE_127771';
npx.Nomination_Process__c='Case Closure Nomination';
npx.Status__c='Nominated';
npx.Survey_Name__c='Technical Support Survey';
npx.Product_Series__c='CONNECT-SECURE';
npx.Survey_Details_URL__c='';
npx.Status_Description__c='test description';
Test.starttest();
insert npx;

test.stoptest();
npx.Primary_Score__c=6;
update npx;


}

}
}


Apex class:


public with sharing class SMXNPXSurveyBL
{  
  
    /*
     * Method which takes a set of NPX Survey records and check for the primary score lessthan or equal to 6 and 
     *then create case if there is no case existed on the NPX Survey record.  
   */
  public static void createCase(List<NPX_Survey_Record__c> newRecords)
    {
    
    String severity;
    String IsAlert = 'N';
    
    Set<Id> nPXIds = new Set<Id>();    
    for(NPX_Survey_Record__c npx:newRecords){
    
        nPXIds.add(npx.id);
    }
    List<case> caseList = new  List<case>();
    List<Case> ListCases = new List<Case>();
    
     caseList=[select id,Casenumber,NPX_Survey_Record__c from Case where NPX_Survey_Record__c in :nPXIds];
     
         if(!nPXIds.isEmpty()){
         
             for(NPX_Survey_Record__c npx:newRecords){                            
                 
                 if(npx.Primary_Score__c <= 6 && npx.Survey_ID__c =='PULSESECURE_127771'){
                      
                         severity='High';
                         
                         IsAlert = 'Y';
                    }
                                       
                  if(caseList.isEmpty() && (IsAlert == 'Y')){
                    Case c=new Case();
                    c.OwnerId=npx.OwnerID;
                    c.parentid=npx.case__c;
                    c.Subject='CPSE Negative Survey for '+npx.Account__r.Name;
                    c.Survey_Details__c ='Primary Score: '+ npx.Primary_Score__c+ '\n Primary Comment: '+npx.Primary_Comment__c;
                    //c.Status=status;
                    c.Priority=severity;
                    c.AccountId=npx.Account__c;
                    c.ContactId=npx.Contact__c;
                    c.Origin='Satmetrix';
                    //c.RecordTypeId=recType.Id;
                    c.NPX_Survey_Record__c=npx.id;
                    c.SurveyDetailsURL__c = npx.Survey_Details_URL__c;
                    ListCases.add(c);
                    
                }
                
                 
             }  
              
              insert ListCases;
        }
    }
    
}


Can you please help me out on this . how to pass this one


Regards,
Isha
can somebody help on this. i finished all the other ones in this trail head. installed the package. first ine worked fine. 
challenge is : 
Edit the AllBadThings() method, as follows:
Replace the if statement with a Where clause
Move the update statement outside of the for loop
Rename the method AllGoodThings()
i changed as below
public class TrailLoop {      
       public static void AllGoodThings(Account a) {
        List<Task> allMyTasks = [Select Id, status, whatId From Task Where whatId = :a.id];
        for (Task t : allMyTasks) {
                            {
                t.status = 'Completed';
                }
            update allMyTasks;
        }
    }
but it is failing with this error

 

String strAccount ;
String StrVersant;
String accQuery = 'Select Id,Name from Account where Id =:AccountId and Id IN(Select Account__c from Pd_Mod__c where Plng_session__r.Name=:strVersant) ORDER BY Name LIMIT 15000';
            accountList= Database.query(accQuery);
            if(accountList!=null && accountList.size()>0){
               for(Account accObj:accountList){
                  strAccount = accObj.name;
               }
            }
I have to send email to all the Record Owner whose Field is updated in Execute Method of Batch Apex. Can anyone help me finding out the solution.
When an Opportunity Owner is creating a New Opportunity, if they press the “Enter” key, the user will receive the following message “Do you want to save this Opportunity?” with buttons for “Yes” and “No”.
 
  • If the user selects “Yes” and all required fields have been completed, the opportunity will save and the opportunity owner will be taken to the newly created Opportunity Record.
  • If the user selects “Yes” before all required fields have been completed, the opportunity owner will receive the normal errors that state certain fields are required.
  • If the user selects “No”, the user will be taken to the “Opportunities” section.
Hi! I have a problem - when I change the opportunity probability from 75% to 100%, automatically changes business date. Up to now everything was okay - the business date stayed the same as it supposed to be. Can anyone help me with this?
hi all,

     I need to create a way to capture when the first response. I then need to measure how long time between when the Case was opened and       when it was first responded. 

I created two fields: 
Time_to_First_Response__c 
First_Response__c

I need to capture the first response and measure the time to first response in a trigger . 

First Response is defined as when the case owner user makes any edit to the case or logs an activity against the case. 

Time to First Response Calculation: 
I need to NOT include when office is closed (nights, weekends, holidays) in calculation. 
Hello Everybody,
I have a question about Bulkification in Flows.
I do not understand how exacty bulkification works as explained in this article: https://help.salesforce.com/articleView?id=vpm_admin_bulkification.htm&type=5

I created a little test:
1) I have a flow called CaseFlow 
User-added image
The flow has 1 input (caseId).
In the first block I query for the case with Id=caseId.
In the second block I insert a child case of the retrieved one.
2) I call the flow 400 times with the following code:
        List<Case> cases = Database.query('Select id from case limit 400');
        for(case c : cases){
            Map<String,Object> inputs = new map<String,Object>{'caseId' => c.Id};
            Flow.Interview.createInterview('CaseFlow', inputs).start();  
        }    

How many DML am I performing with this code?

In the log (In the debug level, set Workflow to Finer) I have something like:

11:05:54.705 (38705612167)|FLOW_BULK_ELEMENT_LIMIT_USAGE|1 DML statements, total 400 out of 150
11:05:54.705 (38705630521)|FLOW_BULK_ELEMENT_LIMIT_USAGE|1 DML rows, total 400 out of 10000
11:05:54.705 (38705704180)|FLOW_BULK_ELEMENT_END|FlowRecordCreate|CreateChild|1|43

I do not understand if the execution of the flow interviews count as separated (and I am executing 400 DML out of 150) or they are bulkified and I am executing a fewer number of DMLs (in this case, which is the batch size)???
I am successfully creating the 400 child cases so, apparently, I'm executing 400 DMLs.....

Thank you in advance
Marco
 
Hi all,
Here is my scenario. I need to give access to the users to children records B if they have access to the parent record A. A and B are in lookup relation. and the owner of A is not this user. Its an admin user. Does anyone have any code sample or starting point I can refer to(other than documentation)? I know it will be a trigger but the problem is the child record won't even exist when they have access to the parent record. The child records are created later,So  I can give access to child record on creation of child records but I am trying to figure out what happens when the user looses access to parent record, they shouldnt see child records either. 
Any help is highly appreciated.

Thank you
Hi there,

I just thought I'll write the results of my journey through the Salesforce APEX REST world. This is not a question, rather a documentation. Please note that I'm more of a newbie rather than an experienced programmer. I'll try to be precise but sometimes I might simply don't know better. In the end it did work for me - after several hours of looking, testing and reading.
What do I want to do?
The primary intention is to offer a form on my web server (NOT Salesforce) for people to register. In our case we already have Accounts and Contacts in our Salesforce system and we want to ask (some) of the contacts to go to our web-site and apply for the restriceted area. They would be supplying their email address, their account number and a password.
Later - after their request has been approved - they gain access to the web server's restricted site (again - NOT Salesforce) by checking the Salesforce data.
What was my first thought?
Easy, I thought. Create some Javascript. The customer loads the JS into his browser. Upon the button pressed event it takes the data from the form and does post it against a REST endpoint at Salesforce. There I would have a REST service - simply a very basic APEX class with some special "comments" - and this class would be doing the thing.
What I did forget...
was that stuff with the security.
First trap was the so-called CORS stuff (Cross-Origin Resource Sharing). The customer's browser is loading code from my web server. And the JS code loaded from this server, running on the customer's client, would be calling something on a different domain - Salesforce. So browsers do not allow this. Unless - well - unless the second server allows it --> you have to whitelist the web server.
I tried this - but it did not work. Basically the message is: you are not allowed to call an APEX REST service if you didn't authenticate yourself. So - how would we be doing this?
Use OAUTH...
Salesforce offers several so-called flows to authenticate a user. It is really worth spending a few minutes to read the help here - https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm&type=5 . The thing is that - at least to the extend I understood the documentation - you either prompt the user for a SALESFORCE UserId and Password throught the standard login screen (which isn't really nice, and which requires every user to have corresponding SALESFORCE license), or you do use some kind of pre-shared secret (my understanding is based upon docs like this: https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/extend_code_cors.htm where it says at the bootom: „CORS does not support requests for unauthenticated resources, including OAuth endpoints. You must pass an OAuth token with requests that require it.“)
I decided to go with the so-called Java Web Token JWT. Well - nice - but then my Javascript would have the pre-shared secret somewhere on the browser. And if it's on the browser it's no secret anymore.... So I did
Get rid of CORS
and decided to implement the connectivity to Salesforce not with Javascript in the browser on the customer's client but using PHP on web server.
The JWT scenario works like this:
- you set up a so-called "Connected app" in Salesforce (Set-up -> Build --> Create --> Apps
- I did specify to use OAuth
- the OAuth policy included:
* Admin approved users are pre-authorized
* Scope includes "Perform requests on your behalf at any time" and "Access and manage your data"
* a digital certificate - I created a selfsigned certificate using openssl (openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365) - I did upload the cert.pem to Salesforce - and the key.pem on my webserver - surely not into the webroot - you know – this file should be kept REALLY confidentially...
- I then did create a permission set to include the connected app and assigned the permission set to a user (AFAIK the APEX REST class to do the work for the service runs at system level - so who-ever this user is - he/she can do a LOT...
So now - what happens?
The PHP code on the server creates a request. It addresses a well-know endpoint and fills in some data. It signs the data with the private key that we did generate earlier. Then it calls the endpoint. Salesforce checks the signature using the certificate, finds the connected app based upon the data in the request and provides a token - a "newly generated password" back to the PHP code.
The PHP code uses this token to authenticate the request that it sends to the Salesforce APEX REST endpoint.
The code
Let me give you some example.
The HTML file on the web server
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>Integration to Salesforce - Test</title> 
</head>
<body>
<!-- Form -->
<form name="applicant" id="applicant" autocomplete="off">
<p>
<label>Email</label><input type="text" id="email" size="64" autofocus>
</p>
<p>
<label>Ext.Account No.</label><input type="text" id="kdnr" size="64">
</p>
<p>
<label>Password</label><input type="password" id="password" size="64">
</p>
<p><button class="btn btn-success" id="btnSubmit" type="button" onclick="btnSubmitOnClick()">Submit</button></p>


<p><span id="insertresult"></span></p>
</form>
<script type="text/javascript" src="md5.min.js"></script>

<script type="text/javascript" src="testsf.js"></script>

</body>
</html>
The testsf.js Javascript on the webserver (md5.min.js is a tool library that also resides on the server - get it in the internet..)
function btnSubmitOnClick() {
	var email = document.getElementById( "email").value;
	var kdnr = document.getElementById( "kdnr").value;
// we won't be storing the password anywhere in clear text - use the md5 coded value - and yes I know - this is NOT secure - but this is a demonstration only
	var password = md5( document.getElementById( "password").value);

// and yes - we should be doing some checks here to make sure we do not get malformed data --> https://stackoverflow.com/questions/295566/sanitize-rewrite-html-on-the-client-side/430240#430240
    
	var xhr;
	var data = 'email=' + email + '&kdnr=' + kdnr + '&password=' + password;

	xhr = new XMLHttpRequest();
	xhr.open( "POST", "jwtbearer.php", true);
	xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded");
	xhr.addEventListener( "load", display_insert);
	xhr.send( data);

	function display_insert() {
		document.getElementById( "insertresult").innerHTML = xhr.responseText;
	}
}
Now for the PHP code in jwtbearer.php on the web server:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL | E_STRICT);
$email = $_POST ['email'];
$kdnr = $_POST ['kdnr'];
$password = $_POST ['password'];

// documentation in https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm&type=5
// code based upon https://developer.salesforce.com/forums/?id=906F00000005HTiIAM

// the following values ought to be defined via $_SERVER ['variables']
// this is the client ID in the connected app
define('CONSUMER_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXXXXXXXXXXXX');
// and this is the secret of the connected app - actually we do not use it
define('CONSUMER_SECRET', '99999999999999');
// the subject is a name of a user. Make sure that
// - the connected application is set to "Admin approved users are pre-authorized"
// - there exists a permission set that has the right to access the connected application
// - this user is assigned to the permission set
// - the connected application has at least the following two scopes: "Access and manage your data (api)", "Perform requests on your behalf at any time (refresh_token, offline_access)"
// - the connected app has attached the certificate for the private key further down
define('SUBJECT', 'user@domain.test');

define('LOGIN_BASE_URL', 'https://test.salesforce.com');

// First step: get an authorization token from Salesforce that allows us to later call the APEX REST service
// we do this using the so-called JWT bearer flow --> https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm&type=5

// this is where we'll getting the token from
$token_url = LOGIN_BASE_URL.'/services/oauth2/token';

// JSon Header
$h = array(
	"alg" => "RS256"	
);

$jsonH = json_encode(($h));	

// ATTENTION: it has to be base64URL encoded!!!
$header = rtrim(strtr(base64_encode($jsonH), '+/', '-_'), '=');

// Create JSon Claim/Payload
$c = array(
	"iss" => CONSUMER_KEY, 
	"sub" => SUBJECT, 
	"aud" => LOGIN_BASE_URL, 
	"exp" => strval(time() + (5 * 60))
);

$jsonC = (json_encode($c));	

$payload = rtrim(strtr(base64_encode($jsonC), '+/', '-_'), '='); 

$jwtToBeSigned = $header.'.'.$payload;

// This is where openssl_sign will put the signature
$signature = "";

// get the private key from a file (and supply the password for this key - ought to be stored in a S_SERVER variable as well
$pkeyid = openssl_pkey_get_private("file:///etc/php5/apache2/mykey.pem", "9999999999");

// Sign the header and payload
openssl_sign($jwtToBeSigned, $signature, $pkeyid, OPENSSL_ALGO_SHA256);
openssl_free_key($pkeyid);

// Base64URL encode the signature
$secret = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

// construct the "assertion" that Salesforce will use to test
$assertion = $header.'.'.$payload.'.'.$secret;

// and from this construct the array of fields to post
$post_fields = array(
	'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
	'assertion' => $assertion
);

// now prepare the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Make the API call, and then extract the information from the response
$token_request_body = curl_exec($ch);
if ( $token_request_body === FALSE) {
    echo "<pre>";        
    echo "Error from curl_exec during JWT bearer token request: " . curl_error( $ch);
    echo "</pre>";   
    return;
}

// so now we got the token - let's extract the relevant info
$token_request_array = json_decode( $token_request_body, true);

$theToken = $token_request_array[ 'access_token'];
$theInstance = $token_request_array[ 'instance_url'];

curl_close($ch);

// now start the real Service call
// salesforce will tell us where EXACTLY we have to ring...
$token_url = $theInstance . '/services/apexrest/hpp/v1';

// remember: the APEX class in salesforce defines the path; the methods in this class correspond to the various types like POSt, GET....
// Content-type has to be correct
$headers = array( 
            "POST " . "/services/apexrest/test/v1". " HTTP/1.1",
            "Content-type: application/json", 
            "Accept: */*", 
            "Cache-Control: no-cache", 
            "Pragma: no-cache",
            "Authorization: Bearer " . $theToken
        ); 

// these are the fields we want to submit to the APEX REST service
$post_fields = array(
	'email' => $email,
	'kdnr' => $kdnr,
	'password' => $password
);


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$service_request_body = curl_exec($ch) ;
   
if ( $service_request_body === FALSE) {
    echo "<pre>";        
    echo "Error from curl_exec during APEX REST call: " . curl_error( $ch);
    echo "</pre>";    
    return;
}
    
curl_close($ch);
echo "Success!";
Now to Salesforce. I addedd two checkbox fields to the Contact standard object - Applied_for_web_access__c and Granted_web_access__c. I also added a text(32) field to store the hashed password: Web_Hash__c.
Here is the sample code for the APEX class serving as the REST service:
@RestResource(urlMapping='/test/*')
global with sharing class testRestInterface {
    @HttpPost
    global static String createApplicationForAccess( String email, String kdnr, String password) {
        Contact[] cList = [Select Id From Contact Where Email = :email and Account.ExtAccountNo__c = :kdnr];
        if ( !cList.isEmpty()) {
            Contact aContact = cList[0];
            aContact.Applied_for_web_access__c = true;
            aContact.Web_Hash__c = password;
            update aContact;
        } else {
/* here I decided to create a lead... */
            Lead aLead = new Lead( Lastname='Unknown web access requestor', Company='unkonwn company', Applied_for_web_access__c = true, Web_Hash__c = password);
            insert aLead;
        }
        return 'SUCCESS';
    }

}
Later in the project I did use Email Actions with Email Templates that get send upon Changes to the Checkboxes caught in Process Builder - but that's another story....

Lessons learned:
- no APEX REST access without authentication
- authentication done on the web server - not on the client
- base64URL encoded values in the JWT bearer section
- pre-authorized users, with permission set

So - hopefully I did not state something totally wrong here and hopefully too this will help somebody someday.





 
Salesforce.com could not email the report to any of the specified recipients. Check that recipients are specified and that they have the appropriate permissions to view the report.

If you get this ^error:

Make sure you also check:
Setup > Customize > Reports & Dashboards > Email Notifications > Allow Reports and Dashboards to Be Sent to Portal Users

Posting this here since it took me a long time to find this checkbox.
 
We have come up with an interesting case management solution using the templates and algorithms of Prediction IO

Step 1: Using email-to-case feature a customer will mail his/her issue to a routing email-address and a Case will get created with Email Subject as Case Subject and Email body as Case Description
 
Step 2: As soon as case is created, Prediction IO will predict the most relevant article from the set of Article Management for the case. After the article is predicted, it will get attached to the Created Case and the status of Case will move to ‘On Hold’. We have trained a model in PredictionIO using the 'text classification' template and as a input to that template we are sending the Case Subject of Closed cases and Article Title associated with those closed cases based on whcih for any new case the most relevant article is predicted.
 
Step 3: After the article is attached to case, an email will be sent to the Case Creator based on predefined SFDC template with the solution article attached as pdf file with the mail. User will be asked whether the solution case article is relevant for your problem or not. And if yes, the case can be closed.

Step 4: If the customer replies that the article seems to be relevant and case can be closed, then the case will get automatically closed.

The best part of this is that it is completely automated, customer just have to mail theproblem