• salesforcerrr
  • NEWBIE
  • 45 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 0
    Replies
Hi,

When using lightning continuation Blogpost the following lines of code are common that present vulnerabilities to XSS

Function in Lightning component JS controller
doInit: function (component, event, helper) {
		var vfBaseURL = "https://" + component.get("v.vfHost");
		// Listen for messages posted by the iframed VF page
		window.addEventListener("message", function (event) {
			if (event.origin !== vfBaseURL) {
				// Not the expected origin: reject message
				return;
			}
			// Only handle messages we are interested in
			if (event.data.topic === "com.mycompany.message") {
				var result = event.data.result;
				var plainText = result.replace(/"/g, '"').replace(/'/g, "'");
				component.set("v.result", plainText);
			}
		}, false);
	},
- window.addEventListener("message", function (event)
--> var result = event.data.result;

Script in Visualforce page: 
<script>
			var lcBaseURL = "https://momentum-efficiency-4004-dev-ed.lightning.force.com";

			// Listen for messages from the Lightning Component
			window.addEventListener("message", function (event) {
				if (event.origin !== lcBaseURL) {
					// Not the expected origin: reject message
					return;
				}
				// Only handle messages we are interested in            
				if (event.data.topic === "com.mycompany.message") {
					var productId = event.data.productId;
					var latency = event.data.latency;
					Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.SimpleContinuationController.getProduct}', productId, latency, function (result) {
						// Send result to Lightning Component
						var message = {
							topic: "com.mycompany.message",
							result: result
						};
						parent.postMessage(message, lcBaseURL);
					});
				}
			}, false);

		</script>

- window.addEventListener("message", function (event)
--> var productId = event.data.productId;
--> var latency = event.data.latency;
--> var message = {
topic: "com.mycompany.message",
result: result
};

Can someone assist on how to use best JSENCODE to secure this? (I have extracted the important lines and copied below the code snippets) Any other recommendations on what might be required? 
My problem is getting code line test on the callback(Object state) class for the continuation using @RemoteAction. There are a lot of test class example on callback(), but none on callback(Object state), and I can’t figure out how to pass the State object in the class for continuation.

When I use Test.setContinuationResponse and Test.invokeContinuationMethod to test @RemoteAction
public static Object callService(), the apex compiler is reporting an error 'System.TypeException: No method 'callback()' on provided controller type.' it looks like system can't realize the 'public static Object callback(Object state)', which has a parameter Object state. in order to verify this, I try to add a new 'public static Object callback() in controller, yes, compiling pass. however I really want to callback(Object state) instead of callback(), so my quesstion is, How to set ContinuationMethod so that compile can realize the public static callback with parameter 'Object state'?

Thanks
Hi, 

I have a custom Apex Endpoint and would now like to test it with Swagger. I have been successful in setting this up with Postman (using for example: http://amitsalesforce.blogspot.com/2017/06/test-salesforce-api-by-postman-rest.html 

Now what I did was convert the Postman collection to a Swagger file and try to authenticate using this one. Currently I am getting this error when hitting authenticate in Swagger: 
<error_description>must use HTTP POST</error_description>

I pasted the Swagger file here: 
swagger: '2.0'
info:
  version: '1.0'
  title: Salesforce Test
  description: 'TODO: Add Description'
host: ap4.salesforce.com
basePath: /services/apexrest/api/Account
securityDefinitions:
  auth:
    type: oauth2
    flow: implicit
    authorizationUrl: 'https://na50.salesforce.com/services/oauth2/token?grant_type=password&client_id=***Consumer Key_Here***&client_secret=***Consumer Secret_Here***&username=*********&password=*****password+securityToken******'
    scopes: {}
    x-skip-client-authentication: false
schemes:
  - https
consumes:
  - application/json
produces:
  - application/json
paths:
  /12345:
    get:
      description: 'TODO: Add Description'
      summary: Connect to Developer set up
      tags:
        - Misc
      operationId: 12345Get
      produces:
        - application/json
      parameters: []
      responses:
        '200':
          description: ''
      security:
        - auth: []
      x-unitTests:
        - request:
            method: GET
            uri: /12345
          expectedResponse:
            x-allowExtraHeaders: true
            x-bodyMatchMode: NONE
            x-arrayOrderedMatching: false
            x-arrayCheckCount: false
            x-matchResponseSchema: true
            headers: {}
          x-testShouldPass: true
          x-testEnabled: true
          x-testName: Connect to Developer set up
          x-testDescription: 'TODO: Add Description'
      x-operation-settings:
        CollectParameters: false
        AllowDynamicQueryParameters: false
        AllowDynamicFormParameters: false
        IsMultiContentStreaming: false

Does someone know what I need to change? What flow to use with Swagger as its currently on the implicit one this might be the issue? 

Thanks
 
Trigger that is inserting the contact ID of an associated contact via Opportunity contact role into custom field on opportunity
trigger UpdateOppConvertContactTrigger on Opportunity (before update) {

    List<OpportunityContactRole> ContactRoles = [SELECT OpportunityId, ContactId
    FROM OpportunityContactRole];

    Map<String, OpportunityContactRole> OppIdToContactMap = new Map<String, OpportunityContactRole>();
    for (OpportunityContactRole ConRole : ContactRoles) {
        OppIdToContactMap.put(ConRole.OpportunityId, ConRole);
    }

    for (Opportunity opp : Trigger.new) {
        if (opp.Opportunity_Contact__c == NULL) {
            OpportunityContactRole newContact = OppIdToContactMap.get(opp.Id);
            opp.Opportunity_Contact__c = newContact.ContactId;
            opp.Type = 'New Customer';
        }
    }
}

Base test 
@isTest
public class BaseTest {

    public static Account newAccount(String name) {
        return new Account(
                Name = name,
                BillingStreet = 'Some street',
                BillingCity = 'Some City',
                Email__c = 'steve@example.com',
                Phone = '0123456789',
                Industry = 'Agriculture'
        );
    }

    public static Contact newContact(String firstName, String lastName, String accountId) {
        return new Contact(
                FirstName = firstName,
                LastName = lastName,
                Phone = '0123456789',
                Email = 'steve@example.com',
                AccountId = accountId
        );
    }

    public static Opportunity newOpportunity(String Oppname, String accountId) {
        return new Opportunity(
                AccountId = accountId,
                Name = Oppname,
                StageName = 'Appointment Booked',
                LeadSource = 'Test',
                Lead_Source_Specific__c = 'Other',
                CloseDate = Date.newInstance(2018, 12, 09)
        );
    }

}

Test class
@IsTest
public class UpdateOppConvertContactTriggerTest {

    @IsTest
    static void testOppInsert() {
        Account testAccount = BaseTest.newAccount('name');
        insert testAccount;

        Contact testContact = BaseTest.newContact('first', 'last', testAccount.Id);
        insert testContact;

        Opportunity testOpportunity = BaseTest.newOpportunity('oppname', testAccount.Id);
        insert testOpportunity;

        OpportunityContactRole testRole = new OpportunityContactRole();
        testRole.OpportunityId = testOpportunity.Id;
        testRole.ContactId = testContact.Id;
        insert testRole;

        update testOpportunity;

        System.assertEquals(testContact.Id, testRole.ContactId);
        System.assertEquals(testContact.Id, testOpportunity.Opportunity_Contact__c);
    }
}

I am getting 100% coverage without the System.assertEquals at the end. However, it keeps failing with ID in the field being Null. How do i find out why my trigger is not firing? is the update method correct that should fire the trigger? 

much appeciated
Hi, I have writted a trigger that grabs the Contact ID from a contact related to the opportunity via OpportunityContactRole and inserts this ID in a custom lookup field Opportunity_Contact__c. 
 
trigger UpdateOppConvertContactTrigger on Opportunity (before update) {

    List<OpportunityContactRole> ContactRoles = [SELECT OpportunityId, ContactId
    FROM OpportunityContactRole];

    Map<String, OpportunityContactRole> OppIdToContactMap = new Map<String, OpportunityContactRole>();
    for (OpportunityContactRole ConRole : ContactRoles) {
        OppIdToContactMap.put(ConRole.OpportunityId, ConRole);
    }

    for (Opportunity opp : Trigger.new) {
        if (opp.Opportunity_Contact__c == NULL) {
            OpportunityContactRole newContact = OppIdToContactMap.get(opp.Id);
            opp.Opportunity_Contact__c = newContact.ContactId;
            opp.Type = 'New Customer';
        }
    }
}
Now I am finishing up the work on the test class which just inserts the stuff and then does an update to the Opportunity: 
 
@IsTest
public class UpdateOppConvertContactTriggerTest extends BaseTest {

    @IsTest
    static void testOppInsert() {
            Account testAccount = new Account();
            testAccount.Name = 'name';
        testAccount.BillingStreet = 'Some street';
        testAccount.BillingCity = 'Some City';
        testAccount.Email__c = 'steve@example.com';
        testAccount.Phone = '0123456789';
        testAccount.Industry = 'Agriculture';
        insert testAccount;

        Contact testContact = new Contact();
        testContact.FirstName = 'firstName';
        testContact.LastName = 'lastName';
        testContact.Phone = '0123456789';
        testContact.Email = 'steve@example.com';
        testContact.AccountId = testAccount.Id;
        insert testContact;

            Opportunity testOpportunity = new Opportunity();
            testOpportunity.AccountId = testAccount.Id;
            testOpportunity.Name = 'Test';
            testOpportunity.StageName = 'Appointment Booked';
            testOpportunity.LeadSource = 'Other';
            testOpportunity.Lead_Source_Specific__c = 'Other';
             testOpportunity.CloseDate = Date.newInstance(2018, 12, 09);
            insert testOpportunity;

        OpportunityContactRole testRole = new OpportunityContactRole();
        testRole.OpportunityId = testOpportunity.Id;
        testRole.ContactId = testContact.Id;

        Test.startTest();
        Database.update(testOpportunity);
        Test.stopTest();

    }
}
I continue to get: 
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateOppConvertContactTrigger: execution of AfterUpdate
caused by: System.NullPointerException: Attempt to de-reference a null object

No idea why / if error is in test or trigger? 

Much appreciated. 
Hi Everyone, 

i have a faitly straight forward Visualforce page that takes the mobile number. I wanted to validate with Javascrip on the client side like below. 
 
<script>
         function jsCheckPhone()  
        {  
          var mobile = document.getElementById('pageId:formId:mobileId').value;  
          var normal = /^\d{10}$/;  
          if((mobile.value.match(normal))  
                {  
                document.getElementById('mobileMessageId').style.color = 'green';
                document.getElementById('mobileMessageId').innerHTML = 'Looks Good!';  
                }  
              else  
                {  
                document.getElementById('mobileMessageId').style.color = 'red';
                document.getElementById('mobileMessageId').innerHTML = '10 Digits Required';  
                }  
        }  
        </script>

And then later in the form I am calling it like this: 
 
<div role="listitem" class="freebirdFormviewerViewItemsItemItem">
                            <div class="freebirdFormviewerViewItemsItemItemTitle">Mobile <span style="color: #db4437;">*</span></div>
                        </div>
                        <div class="freebirdFormviewerViewItemsTextItemWrapper">
                            <apex:inputField onkeyup="jsCheckPhone();return false;" id="mobileId" value="{!contact.MobilePhone}" required="true" html-placeholder="Your answer" styleClass="freebirdText"/>
                        <span id="mobileMessageId"></span>
                        </div>

It does however never display anything next to the field. Could someone let me know what I am missing / If there would be a better way to have a phone number validated in Visualforce? 

Thanks. 
 
Hi, 

the below class is invoked via Process builder and meant to email a dynamic visualforce attachment. 
 
public class EmailInvoked {

    @InvocableMethod
    public static void sendEmail(List<Id> lstId){
        List<String> EmailIds = 'personal@example.com'.split(',');
        PageReference ref = Page.WorkDocket;
        Blob b ;
        b = ref.getContent();

        

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName('WorkDocket.pdf');
        efa1.setBody(b);

        String addresses;
        email.setSubject( 'Check VF From PB' +String.valueOf(DateTime.now()));
        email.setToAddresses( EmailIds  );
        email.setPlainTextBody('Hey there, I am an email Body');
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}

However, I would need to 
1. Not only have this email send to a static address but based on a field in the Case - Site_Email__c 
2. The Visualforce page is currently attached but only the static contect. For example apex:output fields are not rendered. How do i get the ID in the visualforce page to render correctly? 

Thank you. All help much appreciated. 
 
I got a public apex class with the following query in it: 
List<Case> jobs;
  String query='select Id, Account.Name, Time__c, End__c, Status, Type, CaseNumber from Case WHERE Time__c != null AND End__c != null';
  String whereStr='';
And below is my test class: 
 
@isTest
class CaseListControllerTest {
    static testMethod void testCaseList (){
    List<Case> cases = new List<Case>();
    for (Integer count = 0; count < 50; count++) {
        cases.add(new Case (Subject='Test', Status = 'Open'));
    }
        
    insert cases;
   
    Test.startTest();
        CalendarController.findAll();
    Test.stopTest();
    Case ACC = [select phone from Account LIMIT 1];
        System.assertEquals ( String.valueOf(ACC.Subject) ,'Test');
    
}
}

Error:
Currently i am receiving: Compile Error: Method does not exist or incorrect signature: CalendarController.findAll() at line 12 column 9

But how would i test for the string query? 

Thanks
 
Hi,

I have build an page component with the following head: 
<apex:component layout="none" access="global" extensions="CaseImageController">
    <apex:attribute name="case" description="The Service Activity Statement." type="Case" />

Which i want to be able to use the following Controller extension:
 
Public Class CaseImageController {

    String recId;
    
    public CaseImageController (ApexPages.StandardController controller) {
        recId = controller.getId();    
    }
    
    public String getFileId() {
        String fileId = '';
        List<Attachment> attachedFiles = [select Id from Attachment where parentId =:recId order By LastModifiedDate DESC limit 1];
        if( attachedFiles != null && attachedFiles.size() > 0 ) {
            fileId = attachedFiles[0].Id;
        }
        return fileId;    
    }
}

 However, the error i am getting: 
Only StandardController and Apex Code controllers are currently supported

When I try to insert standarController="Case" in the first line of my componet I get the following error instead: 
Unsupported attribute standardcontroller in <apex:component> in ActivityStatement at line 1 column 106

Can somone assist witht this please? Much appreciated. 
Hi, 

I am getting 25% coverage for below test class. I also copied the controller. Could someone assist with this please? Much appreciated. 
 
Public Class CaseImageController {

    String recId;
    
    public CaseImageController (ApexPages.StandardController controller) {
        recId = controller.getId();    
    }
    
    public String getFileId() {
        String fileId = '';
        List<Attachment> attachedFiles = [select Id from Attachment where parentId =:recId order By LastModifiedDate DESC limit 1];
        if( attachedFiles != null && attachedFiles.size() > 0 ) {
            fileId = attachedFiles[0].Id;
        }
        return fileId;    
    }
}
 
@isTest
private class TestImageControllerTest{

      static testMethod void testAttachments()
    {
        Case cc=new Case(Subject='Acme Inc');
        insert cc;
        CaseImageController controller=new CaseImageController(new ApexPages.StandardController(cc));
 
        Attachment attach=new Attachment();   	
    	attach.Name='Test';
    	Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
    	attach.body=bodyBlob;
        attach.parentId=cc.id;
        insert attach;
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:cc.id];
        System.assertEquals(1, attachments.size());
    }
}

 
Hi, 

trying to set up the fullcalendar set up in Salesforce according to: https://gist.github.com/sjurgis/3c9ad1294b1466d7b910

Have imported everyting into my Salesforce org that was needed from the latest version of https://fullcalendar.io/ and named resources (import in visualforce page) 

Visualforce Page: 
<apex:page showHeader="false" standardStylesheets="false" controller="fullCalendar" standardstylesheets="false">
    
    <apex:stylesheet value="{!$Resource.fullCalendarCSS}"/>
    <apex:stylesheet value="{!$Resource.fullCalendarPrintCSS}"/>
    <apex:includeScript value="{!$Resource.fullCalendarMinJS}"/>
	<apex:includeScript value="{!$Resource.jQuery3}"/>
    <apex:includeScript value="{!$Resource.momentJS}"/>

   <body>             
   <script type="text/javascript"> 
      function getEventData() {                         // records are retrieved from soql database
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.fullCalendar.eventdata}',  // controller and method names
            function(result, event){
                if (event.status) {
                    evt =  JSON.parse(result);
                    $('#calendar').fullCalendar({       // html element and library name
                        events: evt                     
                    }) 
                } else if (event.type === 'exception') { 
                    console.log(event.message);
                } else {
                    console.log(event.message);
                }
            }, 
            {escape: false}
        );
    }
    $(document).ready(function() {
        getEventData();
    });
    </script>
    <div id="calendar"></div>
    </body>
</apex:page>

APEX Class:
public class fullCalendar {
    public string eventsJSON {get;set;}
    
    //The calendar plugin is expecting dates is a certain format. We can use this string to get it formated correctly
    static String dtFormat = 'EEE, d MMM yyyy HH:mm:ss z';

    @RemoteAction
    public static string eventdata(){
        calEvent[] events = new calEvent[]{};
        for(Event evnt: [select Id, Subject, isAllDayEvent, StartDateTime, EndDateTime from Event]){
            DateTime startDT = evnt.StartDateTime;
            DateTime endDT = evnt.EndDateTime;
            
            calEvent myEvent = new calEvent();
            myEvent.title = evnt.Subject;
            myEvent.allDay = evnt.isAllDayEvent;
            myEvent.startString = startDT.format(dtFormat);
            myEvent.endString = endDT.format(dtFormat);
            myEvent.url = '/' + evnt.Id;
            myEvent.className = 'event-personal';
            events.add(myEvent);
        }
        
        string jsonEvents = JSON.serialize(events);
        jsonEvents = jsonEvents.replace('startString','start');
        jsonEvents = jsonEvents.replace('endString','end');
        
        return jsonEvents;
    }

    // Class to hold calendar event data
    public class calEvent {
        public String title {get;set;}
        public Boolean allDay {get;set;}
        public String startString {get;set;}
        public String endString {get;set;}
        public String url {get;set;}
        public String className {get;set;}
    }
}

Apex Test:
@isTest
class FullCalendarTest {
	
    static testMethod void testfullCalendar (){
    event[] bulklist= new event[]{};
	for (integer i = 0; i < 200; i++)
    {
        string srnd = string.valueOf(math.random());
        blob rnd = Blob.valueOf(srnd);
        bulklist.add(new event (
            subject=encodingUtil.base64Encode(rnd),
            startDateTime=system.now().addDays(-10+ (math.random() * 10 ).intValue()),
            isAllDayEvent=true     
        ) );
    }
    insert bulklist;
}
}

I get absolutely no error and test is passing as well. But have the following problems:

1. When i actually try to preview the page nothing happens / completely blank page
2. Test is passing but I get 0 Code Coverage for my class 

All help very much appreciated to get this to work. 
 
Hi, 

i would need to visualize all opportunity products (opportunity line items) in one visualforce page.
- also allowing me preferably to create views like with standard record types
- being able to edit records directly from the view

 A simple solution like this is possible for activities: 
<apex:page >
    <apex:enhancedList customizable="true" type="Activity" height="500"/>
</apex:page>
However for opportunity line items the best thing i could find in the forum was post: https://developer.salesforce.com/forums/?id=906F0000000MNcGIAW

Is it possible to have this generalized and not just create a visualforce page listing products from a specific opportunity but all? 

Thank you 

 
Hi,  

would need assistance for getting started with testing apex classes. I basically created a simple class that is just a SOQL query returning a list of accounts owned by a given user: 
global with sharing class AccountRemoter {
    @RemoteAction
    global static List<Account> findAll() {
        return [SELECT Id, Owner.Name, Name, Phone, Email__c, ShippingLatitude, ShippingLongitude 
                    FROM ACCOUNT
               		WHERE OwnerId=:UserInfo.getUserID()];
		}
}

so far so good and all working well in sandbox but after searching and trying to find just some simple test class in order to achieve code coverage... the best i end up with is something like: 
 
@isTest
class AccountsListControllerTest {
	static testMethod void testAccountList (){
    List<Account> accounts = new List<Account>();
    for (Integer count = 0; count < 50; count++) {
        accounts.add(new Account (Name = 'Jack'+count, Phone ='00000000'+count));
    }
        
    insert accounts;
    AccountRemoter cc = new AccountRemoter(new ApexPages.StandardController(new Account()));
    Test.startTest();
        cc.findAll();
    Test.startTest();
}
}

which still gives me two problems: 
1. Constructor not defined: [AccountRemoter].<Constructor>(ApexPages.StandardController)
2. I think I would need some asserts below but i really cannot find a post where there is a simple test class 

Could someone guide me in the redirection and if this has been answered before please guide me in the right direction. After hours I am still unable to locate a solution. 

Thanks