Tuesday, June 18, 2013

Custom Component Controllers and using assignTo

So I have been working with components lately and have been pretty aggravated that I couldn't seem to get the assignTo to work correctly. So I followed the example showen in the documentation (Custom Component Controllers) word for word, and it worked.. but not really.  Once I tried switching the get/set to the way I prefer public String controllerValue {get; set;} it stopped working. I also noticed that if I was to put anything in the constructor it access it, it would create a null error. For example, if you were to use the same example as in the documentation and changed the class to:

public with sharing class sgf_ComponentAssignToIssue {

  public String controllerValue;
    
  public void setControllerValue (String s) {
    controllerValue = s.toUpperCase();
  }
    
  public String getControllerValue() {
    return controllerValue;
  }

  public sgf_ComponentAssignToIssue() {
    if (String.isNotBlank(controllerValue)) {
      controllerValue.toLowerCase();
      return;
    }
    ApexPages.addMessage(new ApexPages.Message(
      ApexPages.Severity.ERROR, 
      'string is blank'
    ));
  }

}

and change the page to:

<apex:component controller="sgf_ComponentAssignToIssue">
  <apex:attribute name="componentValue" description="Attribute on the component." type="String" required="required" assignTo="{!controllerValue}" />
    <apex:pageBlock title="My Custom Component">
      <p>
        <code>componentValue</code> is "{!componentValue}"
        <br/>
        <code>controllerValue</code> is "{!controllerValue}"
      </p>
    </apex:pageBlock>
    Notice that the controllerValue has been upper cased using an Apex method.

  <!-- just adding the following -->
  <br />
  <apex:pageMessages id="messages" />

</apex:component>

the page will error:


If I change the class to:

public with sharing class sgf_ComponentAssignToIssue {

  public String controllerValue {
    get {return controllerValue.toUpperCase();} 
    set;
  }
    
  public sgf_ComponentAssignToIssue() {
    if (String.isNotBlank(controllerValue)) {
      controllerValue.toLowerCase();
      return;
    }
    ApexPages.addMessage(new ApexPages.Message(
      ApexPages.Severity.ERROR, 
      'string is blank'
    ));
  }
}

and leave the page as is, the page will now error:


If I change it so the class looks like this:

public with sharing class sgf_ComponentAssignToIssue {

  public String controllerValue {
    get;
    set {controllerValue = value.toUpperCase();}
  }
    
  public sgf_ComponentAssignToIssue() {
    if (String.isNotBlank(controllerValue)) {
      controllerValue.toLowerCase();
      return;
    }
    ApexPages.addMessage(new ApexPages.Message(
      ApexPages.Severity.ERROR, 
      'string is blank'
    ));
  }

}

The page will work again, but still nothing works in the constructor. And if I change it to say, an Id and update the class to:

public with sharing class sgf_ComponentAssignToIssue {

  public Id controllerValue {get; set;}
  public Account passedAccount {get; set;}
    
  public sgf_ComponentAssignToIssue() {
    if (String.isNotBlank((String)controllerValue)) {
      passedAccount = new Account(Id = controllerValue);
      return;
    }
    ApexPages.addMessage(new ApexPages.Message(
      ApexPages.Severity.ERROR, 
      'Id is blank'
    ));
  }

}

and the page to pass the Id to the controller, you get:
So you can see that the controller does effect the variable but still since I can not use it in the constructor I cant really use it in the component to do anything on load... 

My Question is:
Why cant the class constructor or the getter access the variable being passed from the assignTo?

Tuesday, June 4, 2013

Showing images in your custom Visualforce pages via Attachments

Everyone wants images, profile pictures, logos etc. Sure you can add these via style, but this isn't very practical if the end user is adding them (they dont know, or need to know, how to use static resources). So lets say you have a task to make a page that shows lists of contacts, but they want to see the contacts image, if they have one. If they dont, we will have to show a default user image in its place to keep each contact consistant. 

This is done very simply :-) On each contact record (or any object that you allow attachments on) the user has the ability to attach files and images. So we want to grab them via a relationship query on that object, and then display them on the page. For my example I am only going to show the most recent image per Contact.

First step is to create the page and controller. I called my class (controller) sfg_ContactPhotos so the page so far would look like this:


<apex:page showHeader="true" sidebar="true" controller="sfg_ContactPhotos">

</apex:page>

In the controller we will need a List of Contacts and a few methods to get it all going. Normally this would be a controller extension to the Contact standard controller, but since I just want to show the logic, I dont want to complicate things here. 



public class sfg_ContactPhotos {

  public List<Contact> lstOfContacts {get; set;}


  public sfg_ContactPhotos() {

    //constructor
  }

  private List<Contact> findContacts() {

    //logic for getting contacts
    return new List<Contact>();
  }

}



You may notice that I like to use the {get; set;} instead of the way salesforce normally does it via a get method and set method; this is simply because if it is done the salesforce way, the get method will be hit on every call to the controller and I only need to load the Contacts once. Anyhow, we need to add another variable for the Map of Attachments, a method to build the map, and it wouldn't hurt to wire up the variables to their methods in the constructor. If you notice the Map is a <String, String> which is not the *correct way, it should be Map<Id, Attachment> but due to issue with visualforce and Maps, it has to be String (see Post).


public class sfg_ContactPhotos {

  public List<Contact> lstOfContacts {get; set;}

  public Map<String, String> mapOfPhotos {get; set;}

  public sfg_ContactPhotos() {

    lstOfContacts = findContacts();
    mapOfPhotos = buildPhotoMap(lstOfContacts);
  }

  private List<Contact> findContacts() {

    //logic for getting contacts
    return new List<Contact>();
  }

  private Map<String, String> buildPhotoMap(List<Contact> pContacts) {

    if (pContacts  == null || pContacts.isEmpty()) {
      return new Map<String, String>();
    }

    Map<String, String> returnMap = new Map<String, String>();

    //logic to make the map of attachments
    return returnMap;
  }

}



A few things to note here, if you notice I am passing the list of Contacts into the buildPhotoMap method. I call it 'pContacts' due to it being a 'param' thus the 'p'. Since it is passed, this means that we can control what builds the map, instead of just grabbing the Contacts in their current state. I also check to see if what is passed actually has anything before creating any variables in the class, this is a good practice to get into. Why waste time creating variables if there isn't anything for the method to use? It may only be milliseconds but it can add up, so its good to do the check for null/empty/blank first and if nothing is there, exit the method, not wasting any time. 


Ok, lets add some logic to the class, first we will query for the Contacts and the related Attachments, then pass it to the buildPhotoMap method to get the data set up like we want. In this query we only want the public ones and will order the Attachments by LastModifiedDate 'desc' which pust the newest one first. We will limit the query to 2 just so we dont over load the page/example.


private List<Contact> findContacts() {
    return [select Name,
                   Email,
                   (select ContentType
                    from Attachments
                    where isPrivate = false
                    order by LastModifiedDate desc)
            from Contact
            limit 2];
  }


If you notice I am not querying for any Id's this is because by default SOQL returns the Id of the object so there is no need to specify it in the query. There is also no need for a try catch statement since if there is nothing to return it will simply return null, and in the buildPhotoMap method we are if it is null or empty before using it, thus negating any issues.

Now lets put some logic into the buildPhotoMap method, we will need to iterate over the contact list with a for loop and since the Attachments are in a related query we will need a second for loop over it to get into each attachment on the individual contact record. Once in the Attachments for loop we will need to check what type it is since you can have many different types of attachments, we should check if the ContentType is of type 'image'. (you could of corse add a where clause to the query itself and only return Attachments where ContentType = 'image/%' thus negating the check in the for loop)



private Map<String, String> buildPhotoMap(List<Contact> pContacts) {
    if (pContacts.isEmpty()) {
      return new Map<String, String>();
    }

    Map<String, String> returnMap = new Map<String, String>();
    for (Contact c : pContacts) {
      for (Attachment a : c.Attachments) {
        if (returnMap.containsKey(c.Id)) {
          break;
        }
        if (a.ContentType.contains('image/')) {
          returnMap.put(c.Id, a.Id);
          break;
        }
      }
      if (!returnMap.containsKey(c.Id)) {
        returnMap.put(c.Id, 'none');
      }
    }
    return returnMap;
  }


Since we need a map entry for each contact (so we dont brake the page with an error of 'Map key {ID} not found in map') and we dont want to loop more than we need to, I set it up so it brakes once it detects that the map already contains the contact Id. If it doesn't then it will check if the Attachment is of type 'image/' (normally the types are 'image/jpg' or 'image/gif' etc so using 'image/' will cover all images) and if it is, add it to the map and then brake out of the Attachment for loop and on to the next contact. If however, the Contact doest have any image Attachments, we will add a null value so the map wont brake the page.

Now that we have the controller done, lets focus on the page. We will need an apex:repeat over the contact list and an apex:image to display the default image (incase the user has no images)


<apex:page showHeader="true" sidebar="true" controller="sfg_ContactPhotos">
    <apex:stylesheet value="{!URLFOR($Resource. sfg_customPhotos, '/css/main.css')}" />
 
    <div id="sfg_pageWrap">
        <apex:repeat value="{!lstOfContacts}" var="c">

            <div id="{!c.Id}">
                <h1>{!c.Name}</h1>
                <apex:image url="{!URLFOR($Resource.sfg_customPhotos, '/image/userIcon.png')}" width="50" height="50"/>
            </div>

        </apex:repeat>
    </div>
</apex:page>


As you can see I have some style included via the apex:stylesheet tag, and a default image. We still need to add some conditional rendering and the Attachment Image to the page but first lets take a moment to talk about Resources.

Static Resources are very hand if you know how to use them. First off they are located in setup > develop > Static Resources. Click the new button and you'll see a page like this:

 The name will be the one used in the value="{!URLFOR($Resource.yourResourceNameHere,  ... ", the resource should be public, and the file should be a zip of the folder (if you want to have everything in one spot, otherwise you can just upload an image or a file, but if you want folders they have to be compressed or 'zipped'). Since I am including everything in one resource I have to zip my folders, which look like this on my computer:

So the page should now look like this once we fill it all out:
Click save and then if you need to update it you can click edit and upload the new .zip.

Since I am using folders, I have to travers them like would in any other language to access the items like '/css/main.css' as you can see in the page. Its the same for the image as well, '/image/userIcon.png'. Even if you dont have folders but a zip of lose files, you will need to '/someFileName.css' the '/' is important, without it some browsers (like IE) wont render it correctly.

Ok back to business, lets add the Attachment image to the page and then put in some conditional rendering based off weither the map is empty for that contact, and if so lets show a default image of a user:

<apex:image rendered="{!mapOfPhotos[c.Id] == 'none'}" url="{!URLFOR($Resource.sfg_customPhotos, '/image/userIcon.png')}" width="50" height="50"/>

<apex:image rendered="{!mapOfPhotos[c.Id] != 'none'}" url="{!URLFOR($Action.Attachment.Download, mapOfPhotos[c.Id])}" width="50" height="50" />

SO when we load the page we should see something like this:
...and yes .gif's do work :-)

Monday, May 27, 2013

Bug with apex:selectCheckboxes

The Project:
Make a search with multi-select checkboxes for better filtering. 

The Solution:
Simple right? Just make a page and controller with some <apex:selectCheckboxes> and a <apex:commandButton> to make it all go. 

<apex:page showHeader="true" sidebar="true" controller="sfg_testBugWithActionButton">
<apex:form>
    <apex:outputpanel id="mainWrap">
        <apex:repeat value="{!filterMap}" var="key">
          <div class="filterItem">
            <h2>{!key}</h2>
            <apex:selectCheckboxes value="{!filterKeys[key]}" layout="pageDirection">
              <apex:selectOptions value="{!filterMap[key]}" />
            </apex:selectCheckboxes>
          </div>
        </apex:repeat>
        <apex:commandButton action="{!preformAction}" rerender="renderWrap" value="Submit Action" />
      <apex:outputpanel id="renderWrap">
        {!resultString}
      </apex:outputpanel>
    </apex:outputpanel>
  </apex:form>
</apex:page>



public class sfg_testBugWithActionButton {

  public List<String> fGender {get; set;}

  public List<String> fGrade {get; set;}

  public List<String> fRole {get; set;}

  public String resultString {get; set;}



  public Map<String, List<SelectOption>> filterMap {get; set;}
  public Map<String, String> filterKeys {get; set;}

  public sfg_testBugWithActionButton() {
    filterKeys = new Map<String, String> {
      'Gender' => 'fGender',
      'Grade' => 'fGrade',
      'Role' => 'fRole'
    };
    createfilterMap();
    resultString = 'on Load of page';
  }

  public PageReference preformAction() {
    resultString = 'button action preformed';
    return null;
  }

  private void createfilterMap() {
    filterMap = new Map<String, List<SelectOption>>();
    List<SelectOption> options = new List<SelectOption>();

    for (String s : filterKeys.keySet()) {
      if (s == 'Gender') {
        options = new List<SelectOption>();
        options.add(new SelectOption('Male', 'Male'));
        options.add(new SelectOption('Female', 'Female'));
        filterMap.put('Gender', options);
      }
      if (s == 'Grade') {
        options = new List<SelectOption>();
        options.add(new SelectOption('A', 'A'));
        options.add(new SelectOption('B', 'B'));
        options.add(new SelectOption('C', 'C'));
        filterMap.put('Grade', options);
      }
      if (s == 'Role') {
        options = new List<SelectOption>();
        options.add(new SelectOption('Support', 'Support'));
        options.add(new SelectOption('Sales', 'Sales'));
        options.add(new SelectOption('Marketing', 'Marketing'));
        filterMap.put('Role', options);
      } 
    }
  }
}

(no style so nothing pretty, just to get the idea)

But WAIT! Why isn't anything happening when I click the button? The text next to the button should be changing. hummm Lets put a debug at the top of the method being called by the button and check the logs to see if its hit...

public PageReference preformAction() {
  system.debug('Gender: ' + fGender);
  system.debug('Grade: ' + fGrade);
  system.debug('Role: ' + fRole);
  resultString = 'button action preformed';
  return null;
}

hummm nothing.. not even a mention of the button getting clicked in the logs, let alone my debug statements. Ok I know from experience I can force the button by using the <apex:actionRegion> attribute..

<apex:actionRegion>
  <apex:commandButton action="{!preformAction}" rerender="renderWrap" value="Submit Action" />
</apex:actionRegion>
      
Click and well now the debug statement is being hit, but its not picking up the values in the  <apex:selectCheckboxes> hummmm.. I know I shouldnt need the <apex:actionRegion> so lets remove that and see what happens when i just click the button, without selecting any of the checkboxes first.. Oh shit it works... the values are null, but they should be since nothing is selected.. Ok lets try changing the <apex:selectCheckboxes> to <apex:selectList> and see if they work.. damn, it seems to work, the resultsString is getting updated, but the values are still showing as null in the logs so I guess its not working, but atleast its working better than the <apex:selectCheckboxes>.. 

It shouldn't be anything to do with the maps or repeat but why dont we do this the long way and see if that helps..

<apex:page showHeader="true" sidebar="true" controller="sfg_testBugWithActionButton">
<apex:form>
    <apex:outputpanel id="mainWrap">
      <div class="filterItem">
        <h2>Grade</h2>
        <apex:selectCheckboxes value="{!fGrade}" layout="pageDirection">
          <apex:selectOptions value="{!soGrade}" />
        </apex:selectCheckboxes>
      </div>
      <div class="filterItem">
        <h2>Gender</h2>
        <apex:selectCheckboxes value="{!fGender}" layout="pageDirection">
          <apex:selectOptions value="{!soGender}" />
        </apex:selectCheckboxes>
      </div>
      <div class="filterItem">
        <h2>Role</h2>
        <apex:selectCheckboxes value="{!fRole}" layout="pageDirection">
          <apex:selectOptions value="{!soRole}" />
        </apex:selectCheckboxes>
      </div>
      <apex:commandButton action="{!preformAction}" rerender="renderWrap" value="Submit Action" />
      <apex:outputpanel id="renderWrap">
        {!resultString}
      </apex:outputpanel>
    </apex:outputpanel>
  </apex:form>
</apex:page>


public class sfg_testBugWithActionButton {
  public String fGender {get; set;}
  public String fGrade {get; set;}
  public String fRole {get; set;}
  public List<SelectOption> soGender {get; set;}
  public List<SelectOption> soGrade {get; set;}
  public List<SelectOption> soRole {get; set;}
  public String resultString {get; set;}

  public sfg_testBugWithActionButton() {
    createfilterMap();
    resultString = 'on Load of page';
  }

  public PageReference preformAction() {
    system.debug('Gender: ' + fGender);
    system.debug('Grade: ' + fGrade);
    system.debug('Role: ' + fRole);
    resultString = 'button action preformed';
    return null;
  }

  private void createfilterMap() {
    soGender = new List<SelectOption>();
    soGender.add(new SelectOption('Male', 'Male'));
    soGender.add(new SelectOption('Female', 'Female'));
      
    soGrade = new List<SelectOption>();
    soGrade.add(new SelectOption('A', 'A'));
    soGrade.add(new SelectOption('B', 'B'));
    soGrade.add(new SelectOption('C', 'C'));
    
    soRole = new List<SelectOption>();
    soRole.add(new SelectOption('Support', 'Support'));
    soRole.add(new SelectOption('Sales', 'Sales'));
    soRole.add(new SelectOption('Marketing', 'Marketing'));
  }
}

No joy, same problem with or without the repeat when using <apex:selectCheckboxes>. Now lets try the same thing but with <apex:selectList> instead.. And it works! But why wouldn't it work when in the repeat or with the <apex:selectCheckboxes>? I also made sure it works when I added the attribute multiselect="true" to them, since that is what I would need anyhow if I had to use Lists over checkboxes.

So lets review: 
Right now it seems that anything with the <apex:selectCheckboxes> wont work (regardless of version since I did try bumping it back on both the page and controller). When trying to be dynamic and using a repeat to populate the Lists it fails as well for both <apex:selectCheckboxes> and <apex:selectList>. But if you do it the long way, you can get <apex:selectList> to work at the very least, although that means more fighting with style to get it to look like checkboxes if that is the desired effect. 

*sad panda*

I posted a simpler test of this not working here: Stackoverflow

**Update**
ANSWER FOUND and so not a bug lol bellow is the update made to the controller, and no update was needed to the page(see page at top of post for code):


public class sfg_testBugWithActionButton {

  public List<String> fGender {get; set;}
  public List<String> fGrade {get; set;}
  public List<String> fRole {get; set;}

  public String resultString {get; set;}

  public Map<String, List<SelectOption>> filterMap {get; set;}

  //this had to changed from Map<String, String> to what you see below
  public Map<String, List<String>> filterKeys {get; set;}

  public sfg_testBugWithActionButton() {
    //this was also added, and helped make it all work
    fGender = new List<String>();
    fGrade = new List<String>();
    fRole = new List<String>();

    // and so this got updated as well to use the param and not a string
    filterKeys = new Map<String, List<String>> {
      'Gender' => fGender,
      'Grade' => fGrade,
      'Role' => fRole
    };
    createfilterMap();
    resultString = 'on Load of page';
  }

  public PageReference preformAction() {
    resultString = 'button action preformed';
    return null;
  }

  private void createfilterMap() {
    filterMap = new Map<String, List<SelectOption>>();
    List<SelectOption> options = new List<SelectOption>();

    for (String s : filterKeys.keySet()) {
      if (s == 'Gender') {
        options = new List<SelectOption>();
        options.add(new SelectOption('Male', 'Male'));
        options.add(new SelectOption('Female', 'Female'));
        filterMap.put('Gender', options);
      }
      if (s == 'Grade') {
        options = new List<SelectOption>();
        options.add(new SelectOption('A', 'A'));
        options.add(new SelectOption('B', 'B'));
        options.add(new SelectOption('C', 'C'));
        filterMap.put('Grade', options);
      }
      if (s == 'Role') {
        options = new List<SelectOption>();
        options.add(new SelectOption('Support', 'Support'));
        options.add(new SelectOption('Sales', 'Sales'));
        options.add(new SelectOption('Marketing', 'Marketing'));
        filterMap.put('Role', options);
      } 
    }
  }
}


HAZA! :-)

Tuesday, March 26, 2013

Benchmark Testing: maps vs for-loop

Speed and efficiency should always be in the forefront of a developers mind when writing code. This, most agree on. What is not agreed upon is how that should be accomplished. Each developer has their our own preferences on how it should be written for various reasons. Usually it's due to how they were taught or trained, maybe its because it is more aesthetically pleasing or reads cleaner. Regardless of the cause, the effect is that the code could have performed more efficiently or at a faster rate. There is always more than one way to accomplish a task, benchmark testing is used to prove what methodology is the faster one, although might not be the prettiest. 

The Argument:

Jim thinks that it is faster to collect data via a for-loop:

Set<Id> accountIds = new Set<Id>();

for (Account a : [select Id from Account]) {
  accountIds.add(a.Id);
}
someMethod(accountIds);

Jane however insists that it is faster to do it via SOQL to Map:

Map<Id, Account> accounts = new Map<Id, Account>(
  [select Id from Account]
);
someMethod(accounts.keySet());

After much debate, a few harsh words and a broken pen, a bet was struck.

The Test:

A test class can be written, alternatively this could be done in 'execute anonymous' but with a test class the real data wont be effected as it would the other way. The tests will run different amounts of data through each pattern and record the time it took for the comparison. First the data needs to be created that they will iterate over. 


private static void createAccounts(String pName) {
  Account a;
  List<Account> accounts = new List<Account>();
  for (Integer i = 0; i < 200; i++) {
    accounts.add(a = new Account(Name = pName + i));
  }
  insert accounts;
}

The name needs to be unique for each Account created, to help accomplish this a string will be passed in to add to it when the account is being created. Since Salesforce has govonerner limits in place, only 200 records can be created at a time and so requiring a second method to call createAccounts() and allow more than 200 to be made at a time. 

private static void setupTests(Integer pLimit) {
  for (Integer i = 0; i < pLimit; i++) {
    createAccounts(String.valueOf(i));
  }
}

To test the for-loop and map, a timestamp is logged at the start and end of the method in milliseconds (this makes the comparison easier). Since each is using the data created in the test, the amount being iterated over is known and no limit is needed in the SOQL statement.


private static Long runViaForLoop() {
  Long lStart = DateTime.now().getTime();
  Set<Id> accountIds = new Set<Id>();
  for (Account a : [select Id from Account]) {
    accountIds.add(a.Id);
  }
  return DateTime.now().getTime() - lStart;
}

private static Long runViaMap() {
  Long lStart = DateTime.now().getTime();
  Map<Id, Account> accounts = new Map<Id, Account>(
    [select Id from Account]
  );
  return DateTime.now().getTime() - lStart;
}

Its time to actually do some testing. The first test should be over a low number of records like 1 or 5 and slowly working up to larger numbers like 10k. Debug statements are necessary to see the output of the numbers in the logs after the tests complete. This will show which pattern took less time to iterate over the various record sizes, and thus show which one is better to use, and who wins the bet!

private static testmethod void compaireTime() {
  setupTests(1);
  system.debug('for-loop: ' + runViaForLoop()  + 'ms');
  system.debug('map: ' + runViaMap() + 'ms');
}

After the tests run, the output will show how long each took to complete the same task. 

DEBUG| for-loop: 36ms
DEBUG| map: 10ms

Looks like the Map is the winner. Unfortunately though, Jim is a sore loser and since there are other factors that can effect the output, its best to run the tests a few times along with expanding it to larger sets of records such as 4k and 10k:

private static testmethod void compaireTime() {
  setupTests(20);
  system.debug('4k for-loop: ' + runViaForLoop() + 'ms');
  system.debug('4k map: ' + runViaMap() + 'ms');
  setupTests(30);
  system.debug('10k for-loop: ' + runViaForLoop() + 'ms');
  system.debug('10k map: ' + runViaMap() + 'ms');
}


DEBUG| 4k for-loop: 876ms
DEBUG| 4k map: 138ms

DEBUG| 10k for-loop: 1777ms
DEBUG| 10k map: 246ms

DEBUG| 4k for-loop: 787ms
DEBUG| 4k map: 107ms

DEBUG| 10k for-loop: 2234ms
DEBUG| 10k map: 340ms

DEBUG| 4k for-loop: 1580ms
DEBUG| 4k map: 113ms

DEBUG| 10k for-loop: 1740
DEBUG| 10k map: 220


DEBUG| 4k for-loop: 796
DEBUG| 4k map: 115

DEBUG| 10k for-loop: 1898
DEBUG| 10k map: 279



The graph above shows the average of 20 tests, and it shows that as the record size increased, the time saved using maps speaks for itself. Jane is clearly the victor here, and Jim has to pay up. Numbers always win arguments.