Showing posts with label Apex. Show all posts
Showing posts with label Apex. Show all posts

Wednesday, 16 May 2012

Working with Content in Apex

So, it's been a long while since I last posted here an this one is going to be a short one for the techies amongst us. I recently had some work to do around Content and using a trigger to take the latest version of a template and create a copy linked to a custom object and also share it in a different workspace as a specific piece of documentation. Now, if you haev been around Salesforce long enough, you'll know that when Content first came out it was completely untouchable with Apex and today, I am happy to say, this has now changed. Onto the solution... I first created a custom setting which would hold the Ids of the Workspace(s) I would be using (to get around the hard coding issue and depolyment from sandbox to production) and wrote some very simple code to retreive this:
 public static CPM_Documentation_Settings__c getWorkspaceIds() {
     // Retrieve the custom setting and get the Id of the workspace
     CPM_Documentation_Settings__c documentSettings = [SELECT Document_Template_Workspace_Id__c, Document_Workspace_Id__c FROM CPM_Documentation_Settings__c][0];
     return documentSettings;
     
    }
Whilst not very robust or defensive it met the immediate need to get the Ids back that I needed. The next job was the meat of the issue, how to pick up the latest version of any templates and create new versions in the documentation workspace and link them to the custom object. The First thing I needed to do was get all the latest versions of the templates:
    // Get the Workspace
        CPM_Documentation_Settings__c settings = ProjectTriggerUtilities.getWorkspaceIds();
        
     ContentWorkspace templatesWorkspace = [SELECT Id FROM ContentWorkspace WHERE Id = :settings.Document_Template_Workspace_Id__c];
     ContentWorkspace projectWorkspace = [SELECT Id FROM ContentWorkspace WHERE Id = :settings.Document_Workspace_Id__c];
        
        // Get the list of document templates and their current published version Ids
        List templates = [SELECT ContentDocumentId FROM ContentWorkspaceDoc WHERE ContentWorkspaceId = :templatesWorkspace.Id];
        List templateIds = new List();
        for (ContentWorkspaceDoc doc : templates) {
         templateIds.add(doc.ContentDocumentId);
        }
        List contentDocuments = [SELECT LatestPublishedVersionId FROM ContentDocument WHERE Id in :templateIds];
        
        List latestVersionTemplateIds = new List();
        for (ContentDocument cs : contentDocuments) {
         latestVersionTemplateIds.add(cs.LatestPublishedVersionId);
        }
Now that I had a collection of all the latest versions of templates I simply needed to create the new versions linked to the custom object:
//loop through all the templates and pull back the latest published version of each of them
        List latestVersionOfTemplate = [SELECT c.VersionData, c.Title, c.Supplier_Brand__c, c.Relevant_Sector__c, c.Reference__c, c.PublishStatus, c.Printed_Version_Available__c, 
                                                               c.Printed_Format__c, c.PositiveRatingCount, c.PathOnClient, c.Origin, c.NegativeRatingCount, c.Industry_Sector__c, c.Id, c.FirstPublishLocationId, 
                                                               c.FileType, c.FeaturedContentDate, c.FeaturedContentBoost, c.Description, c.Customer_Facing__c, c.ContentDocumentId, c.Classification__c, 
                                                               c.Brand_Relevance__c 
                    FROM ContentVersion c
                    WHERE ID in :latestVersionTemplateIds];
        for (Project__c p : projects) {                    
         //create the new documents from the templates
         List newProjectDocuments = latestVersionOfTemplate.deepClone();
         for (ContentVersion cv : newProjectDocuments) {
          cv.FirstPublishLocationId = settings.Document_Workspace_Id__c;
          cv.project__c = p.Id;
          cv.ContentDocumentId = null;
          cv.Title = p.Project_Name__c + '_' + cv.Title;
          cv.Description = '';
         }
         insert newProjectDocuments;
        }
And there you have it, we now have the ability to create new content based on existing templates that exist in SFDC content. There is still some fun to be had unit testing and there are still some gotchas in there they are easy to workthough. If you have any questions please let me know by commenting and I'll do my best to steer you in the right direction.

Wednesday, 16 November 2011

VF Woes

Very quick blog this week and it's around an issue I had allocating dynamic Ids to Apex Input fields.

I had a recent requirement that needed me to change the values in some input fields in a targetted way on a VF page. My first thought was to assign a dynamic ID to the <apex:inputfield> only to find that you need concrete values in here.

Found a clever way round this that allows you to find fields by their <apex:inputfield styleclass="{!variable}"

As the JavaScript function getByElementClass is not support in all browsers I needed to write something quick and functional (read dirty) that did the job without using any external libraries or Frameworks i.e. jQuery Here is a very simple JS function that will retrieve all the elements of a certain classname to allow you to 'do stuff' to them.
function getElementByClassName(cl) {
    var elements = [];
    var elem = document.getElementsByTagName('input');
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].className.indexOf(cl)!=-1) elements.push(elem[i]); 
    }
    return elements;
}; 
Not rocket science but you can extend it to use regular expressions etc... and all you need to do it pass it the classname you are looking for. Won't solve a lot of problems but it definitely solved one for me today :)

Monday, 17 October 2011

The Lazy Unit Tester

My take on unit tests? Essential!

Never mind that SalesForce.com forces 75% code coverage on any code written. Even if this mechanism wasn't there, I would still insist on them being present on any solution implemented by myself or my team.

A unit test is, at its most basic level, code that tests code! It's not a replacement for smoke, functional or system testing; it's a mechanism which helps improve the quality of code written by developers.

If you’re building a car, it’s the sum of all its parts. The parts are manufactured individually, then put together and at the end of it you have a working car! Quite a simple process, like a jigsaw puzzle, but a lot can go wrong in this process.

Let's take the wheels on the car. For the car to run you need four wheels, each with tyres. They all need to be the correct size, shape and inflated to the correct pressure to be useful. If one of those wheels is square, the wrong size or is flat then this will affect the operation of the car and make it less than desirable to drive or own.

When buying a new car, you hope the manufacturer tests the individual components (in this example the wheels), as well as the overall function of the car.

Now, onto the geekery, let's take this code example

public class Wheel {
    public static String defaultBrandName = 'Default Tyres Inc';
    public static int defaultSize = 14;
    public static double defaultPressure = 33;

    public String brandName;
    public int size;
    public double pressure;
 

    public Wheel() {
        this.brandName = defaultBrandName;
        this.size = defaultSize; 
        this.pressure = defaultPressure;
    }

    public Wheel(String brandName, int size, double pressure) {
       this.brandName = brandName;
       this.size = size;
       this.pressure = pressure; 
    } 

    // Some Accessors and Mutators for the instance variables
}

public class WheelFactory {
    public static Wheel getWheel() {
        return new Wheel();
    }

    public static Wheel getCustomWheel(String brandName, int size, double pressure) {
        return new Wheel(brandName, size, pressure);
    } 

}
It's quite clear how this now works. We go to the wheel factory and either ask for a default tyre or we specify what kind of tyre we want, as the meerkat says 'Simples'. but what would be the best way to test this to enable me to deploy it to a SDFC production org? Not much I hear you say, but here is an example of the type of thing I have seen.
@isTest
public Class WheelFactoryTest {

    public static testMethod void myUnitTest() {
        Wheel w = WheelFactory.getWheel();
        Wheel w1 = WheelFactory.getWheel('Pirelli', 20, 33);
    }
}
And there is it, as far as Force.com is concerned, a perfectly valid unit test! It makes the 75% test coverage requirement and took about 30 seconds to write. Job done! Let me ask you this though, what is my unit 'TEST' actually testing? The simple answer is that it's testing that the WheelFactory and Wheel classes compile and can be called. It's quite frankly a waste of 30 seconds and this test is useless! Is a Wheel being returned? or is it returning a null? What brand is it? What size? What pressure? We just don't know from this test! Below is what I would consider a better test of this:
@isTest
public Class WheelFactoryTest {

    public static testMethod void wheelFactoryGetWheelNoParamsTest() {
        Wheel w = WheelFactory.getWheel();
        System.assert(w != null);
        System.assert(w.getBrandName() == Wheel.defaultBrandName);
        System.assert(w.getSize() == Wheel.defaultSize);
        System.assert(w.getPressure() == Wheel.defaultPressure);
    }

    public static testMethod void wheelFactoryGetWheelWithParamsTest() {
        String brand = "My Brand";
        int size = 17;
        double pressure = 35;
        Wheel w = WheelFactory.getCustomWheel(brand, size, pressure);
        System.assert(w.getBrandName() == brand);
        System.assert(w.getSize() == size);
        System.assert(w.getPressure() == pressure);
        
}
Hopefully you can see the improvements here?
  1. We are testing each method in a clearly separate way so if one method fails we know instantly which one is broken
  2. We are using asserts to guarantee that we are getting the correct results! When you see a unit test with no asserts you need to change that! 95% of the time there is no excuse for a unit test with 0 assertions this is testing more than just coverage!
  3. We are protected from change! Because we are using the static default variables from the WheelFactory class in our tests, if those defaults change our unit test does not need modifying, this is basic coding 101, don't use magic numbers!
  4. I am actually testing that the tyres are the correct size, pressure and brand! Wouldn't you do that in real life if you were buying tyres for your own car?
Hopefully people will find this useful and when they get given a unit test to write will do the right thing and do it properly and understand the importance of a well constructed unit test!