Tag: Salesforce

Apex: How to Dynamically Tell if a Salesforce Field Exists

How to Dynamically Tell if a Salesforce Field Exists

Lately, I’ve been working on a lot of dynamic apex and soql. I had a requirement to develop a custom appexchange app that could be dynamically querying objects based on a mapping that the admin had supplied and had stored in custom settings.

Originally, I was querying to see if the field existed and returning true if a result was received but this ended taking a lot longer than doing a describe.

I wasn’t able to find any information on how to really tell if a field exists or not. Without further ado, doesFieldExist will return true if the object and field both exist. If the object has been removed and the code hasn’t caught that it will also return false. And finally, if the object exists but the field doesn’t it will return false.


public boolean doesFieldExist(String objName, string fieldName)
    {
    	try {
    		SObject so = Schema.getGlobalDescribe().get(objName).newSObject();
    		return so.getSobjectType().getDescribe().fields.getMap().containsKey(fieldName);
    	}
    	catch(Exception ex) {}
    	
    	return false;
    }

How to have a Visualforce Page Download as a pdf

Salesforce Logo

When creating applications it’s a pretty common request to be able to create a formatted report or file in pdf file format.

For the most part, most customized pages and data can be easily converted into a PDF file without having to make many changes. In Salesforce, we can change customized Visualforce pages to create a pdf file by using the renderAs property and set the value to pdf.

Continue reading

Security in Salesforce

Salesforce Logo

Salesforce has quite a bit of built in security; and has lots of security features that can be customized. Access to most parts of the Salesforce / Force.com platform isn’t actually available until a user has been authenticated.

A few weeks ago, I began studying for Admin Certifications, and was fortunate to find this photo on twitter that @SalesforceBen had shared.

Security in Salesforce House

Security in Salesforce can basically be broken up into profiles and roles. Although they sound pretty similar, profiles and roles do have some differences. Profiles determine record privileges, and determine what the user can do. Profiles also control some salesforce system privileges. Roles or “Role Hierarchy” allows the user to access subordinate’s records, but doesn’t allow upward access.

While Salesforce has a lot of built in security, there’s still some of the standard risks such as Cross Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and SQL Injection (SOQL Injection). The Salesforce Security Guide can help reduce some of these risks.

Book Review: Practical Salesforce.com Development Without Code

Practical Salesforce.com Development Without Code

Practical Salesforce.com Development Without Code written by Phil Weinmeister has been recently released. I think the book really targets those new to the Salesforce platform and does a wonderful job of providing examples and providing a reference that will be useful in the future.

Phil Weinmeister has done a phenomenal job putting together some different scenarios where it makes absolute sense to make use of the declarative functionality that Salesforce provides. As a developer I’ve struggled quite a bit when to use “clicks not code” and feel that Phil has great examples that would be useful to most Salesforce Admins and developers to learn from.

Some of the topics covered include workflows, approvals, process builder, validation rules, and more.

The chapter on object and field level permissions in Salesforce is really well written. I really wish this book had existed when I was first starting to use Salesforce.

Overall, I recommend using the book to learn the declarative features of Salesforce.

Salesforce Quick Deploy

Releasing changes from a sandbox into production Salesforce can be an interesting time as a developer.

As your instance gains more and more code, and tests, the amount of time it takes for changes to deploy increases.

Quick deploy is a relatively new feature that can deploy components up to 96 hours after they have been validated. This can be incredibly handy, if you are needing to deploy changes that may cause a temporary service interruption or invalidate a page’s viewstate.

My personal favourite use is starting the validation at the end of the day and then being able to deploy first thing.

Salesforce Spring15 Test Class Additions

Salesforce has finally introduced a way to create test data for an entire test class; this will be a huge time savings for developers.

The rollback of records created during execution happens at the end of the test class’ execution. By only inserting records once, we should see tests run faster and require less system resources.

Lately, I have been updating all of my test classes to use this new @testSetup annotation. One thing to keep in mind, is that it will not set static variables and has a bug for package developers.

Here’s some sample code:

@isTest
private class join_Controller_Test {

	@TestSetup static void CreateTestData() {
		Util_TestSetup.createSettings();
		Account acc = Util_TestSetup.createAccount();
		Util_TestSetup.createContact(acc.Id);
		Util_TestSetup.createOpportunity(acc);
	}

	static testMethod void Test_Load() {

		Account acc = [select Id from Account];

                PageReference p = new PageReference('apex/internal_join');
                p.getParameters().put('acc', acc.Id);

                Test.setCurrentPage(p);
         
                test.startTest();

                internalJoin_Controller controller = new internalJoin_Controller();
		system.assertEquals(null, controller.OnLoad() );
		system.assertNotEquals(null, controller.acc );

                test.stopTest();
	}
}

I hope that the addition of @testSetup will finally result in better tests on Salesforce. As most programmers with test experience know, testing in Salesforce isn’t usually true unit testing.

Most are usually coded to be integration tests instead. Unit tests are tests that written to verify small sections (“units”) of code; integration testing is testing how the different units work together.

Another common, and disturbing trend, is that most programmers are simply coding unit tests to just get the 75% coverage and not using asserts. By using asserts, the tests can help significantly reduce bugs before code leaves development.

Salesforce Spring15 Including Mapping Features

Salesforce’s Spring 15 release is going to include mapping and geolocation for address fields. I believe, location based features started appearing before I started using Salesforce.

Even more exciting, is that visualforce will include a map component. The mapping component appears to be using Google Maps, but this could probably change.

The new mapping component uses JavaScript to zoom, and move around.

If you get an error when including the maps that reads something like this: “visualforce maps are not enabled for your organization. please contact your administrator” you will need to enable them by following the below directions.

How to Enable in Pre-Release
Setup -> Build -> Customize -> Maps & Location -> Settings. Read the disclaimer and click Okay or Agree.

Including the Map in Visualforce is incredibly easy; it can be done in basically one line of code. The component is simply apex:map.



If you get an error when trying to save the page, make sure your page version is at least 32.

Dreamforce 2014 Notes: Write Apex Tests Using Best Practices

One of the hands on training sessions I attended was “Write Apex Tests Using Best Practices” which really proved to me that a lot of what I believed and was doing were right.

Without further ado, here’s my notes:


Goals for tests

  • Auomated methods that verify application integrity
  • Future Proof
  • Proactively Identify Problems before they enter production
  • Salesforce Runs all customer tests before updates
  • Postive tests & Negative tests
  • Classes that are demarcated by the @isTest annontation won’t count against Apex code limit
  • contain member methods that can only be contained & used in a test
  • tests always have a void return type & no params
  • tests are always static
  • single autonomous transaction
  • only heap space, governor, etc
  • tests should insert their own test data
  • tests should be able to handle uncaught exceptions, etc
  • tests should have assertions to determine validity

Tests Leave No Footprint

  • Apex tests will not commit changes. SOQL still finds records
  • will not performs callouts to external web services
  • will not send outbound email

 

Tests Expect to Work with Mock Data

  • static resources can be used to stage test data in a cache
  • SOSL searches will not find pre-existing records
  • SOQL queries will only find pre-existing records for the following objects:
    • User
    • Profile
    • Organization
    • RecordType
    • For all other objects, SOQL visibility may be overridden with @isTest(seeAllData=true)

Governors

  • verify code is bulk ready
  • pass up to 200 records

Verify End State

  • using assertions

Best Practices

Don’t Depend on Pre-Existing Data

  • Avoid SOQL to initalize SOQL using SeeAllData=true
    • less portable
    • inconsistent results
  • Utilize mock data
  • Call Test.loadData() in a test method to populate
  • Create reusable mock data factories
  • Triggers should never contain business logic, they should only contain calls to classes
  • Use a Naming Convention like NameOfClass_Test
  • Exclude mock data initialization and result verification actions from governor calculations
  • Create separate tests with narrow goals

Challenges

  • blue boxes: test logic
  • grey boxes: business logic

Testing Visualforce Controllers

  • Mimic VisualForce page interactions by explicity calling methods
    • Form fields, eg form.Name use getter/setters
  • Test controller extensions by mocking the controller that was extended

 

Test.startTest synchronously runs asynchronous Apex

Testing Callouts

  • developers need to implement mock calls and responses that do not access the web services
  • setMock() needs to be run to do the fake response and call out

Testing Record Access

  • use System.runAs() methods to verify test users can find records that were shared with apex
  • using System.runAs() is a best practice.

Dreamforce 2014 Notes: Writing Apex and Visualforce Using Re-usable Patterns

Why use patterns:

  • patterns help us be more efficient
  • patterns describe reusable solutions to common problems

Bulk Processing

  • Caching
  • create triggers w/ ability to process hundreds of lookups
  • challenge: queries, DML, memory
  • collect all keys from trigger object in Set Object
  • Query once using SOQL in clause with key set
  • cache results in map object
  • look up related values using map key

Apex Summary Rollup

  • Need to roll up from a child to a parent in a lookup relationship
  • No declarative option for rolling up in a lookup relationship
  • Identify parent IDs affected by change in child.
  • perform an aggregate query on child records
  • update parents using IDs

Configuration Abstraction

  • Manage values that change from environment to environment
  • Maintainability
  • Ease of use

Pagination

  • display records one page at a time
  • performance and maintainability
  • StandardSetController

Search And Sort

  • Allows users to apply search criteria and column sort
  • challenges: Performance and maintainability
  • reusuable Apex and component framework for Search and Sort
  • Dynamic SOQL to modify Where and Order by query clauses

http://developer.force.com/cookbook/recipe/trigger-pattern-for-tidy-streamlined-bulkified-triggers

Looking Back at Dreamforce 2014

Welcome to DreamforceI was really blessed to be able to attend Dreamforce and learn even more about Salesforce.

While attending there, I attended a lot of the different keynotes and saw a lot of the new exciting features in action.

Dreamforce Sessions

At Dreamforce there was dozens of interesting sounding sessions. There were a few different ones that really stood out to me and offered interesting and new material to me. I believe that a lot of the sessions were recorded and able to viewed at a later date which is really exciting and available on youtube here.

One of my favourite sessions was Advanced Development using Apex Design Patterns by Robert Nunemaker. The vide is one if the hundreds uploaded by Salesforce to youtube here.

New Product Announcements

Before attending Dreamforce, I didn’t realize that Salesforce made a lot of its new product announcements there. Some of the new products they announced were: Lightning Components, Process Builder, Salesforce Wave,

Wave / Analytic Cloud

By Far, Wave was the most interesting announcement at Dreamforce 2014. It is a fairly dynamic business intelligence product that is optimized for use on mobile devices. What’s most awesome about Wave is that it will allow for on the spot and completely interactive exploration by business users rather than the static generated reports that have been prewritten.

Duplication Prevention

Through the use of fuzzy logic and other logic it will now be possible to stop duplication from occurring within Salesforce.

Sale Reach

Sales Reach units the power of Pardot, Communities and Sales Cloud into one system. Apparently, it will be able to do popup notifications on the Salesforce1 Application and assist with Leads/Prospect Tracking.

Lightning

Lightning is all about reducing development time and code. Lightning is basically a component framework and new set of tools that make building apps and making automation much faster.

Lightning Components allow developers to create reusable components for use in building apps. Lightning seems to be an event-driven architecture that makes use primarily of JavaScript and model-view controller architecture.

Process Builder allows business processes to be automated more easily and in a visual way.

Lightning Connect is the ability to connect to external data sources and with point and click be able to incorporate the data into Salesforce. The basic idea is that gone are the days of legacy systems and data silos, it would now be possible to use this data in Salesforce and with Wave.

Service Cloud

Smart Agent Console is designed to make it easier to provide good customer service to customers by making searching more intelligent, and where applicable making it possible to show sales data and billing data. It’s no secret that more competent agents allows companies to offer better service with less agents, reducing their service costs.

Community Cloud

Community Designer offers a few different themes that out of the box allow businesses to better connect to customers and reduce support costs. Community Designer allows new communities to be deployed by writing no-code and using point and click.

Topics allow users to access all of the relevant information in one place and even follow it to always stay up to date.

I’m so excited for Dreamforce 2015 and can’t wait to go.

Salesforce Development Tips for the Novice

Salesforce Logo

For the last eleven months or so, I’ve been working a lot as a salesforce developer.  In this time, I’ve learned an incredible amount about Salesforce. This blog article is a culmination of all the different things I’ve experienced and learned along the way. The syntax for Salesforce Apex is very similar to Java, but there’s certainly some different challenges.

For the most part, I’ve become a lot more concerned about the use of resources. Salesforce.com is a multi-tenant environment; this means that resources are shared amongst many. As a result, Salesforce must impose some limits, these limits are called governor limits can be found through out the system.  One of the most common limits is the number of SOQL queries that can be done in a transaction and the number of lines of code that can be run.

The easiest way to get around these limits isn’t to look at using Future Methods (See my blog post called “What are Future Methods “) or other techniques, instead try to use native Salesforce functionality like workflows. For me, avoiding governor limits has been one of the most frustrating parts of developing in salesforce / apex. My first time experiencing a governor limit was in a long loop that queried the Primary Contact for an Account. I would have been far better off using the SOQL binding and then looping through the results after. (And it proved to also be faster when I ended up testing it.) In development, it’s very difficult to hit governor limits. SOQL queries should be avoided in loops.

Triggers should always be coded for bulk processing. Queries and operations should usually be done on some sort of collection like a list. It’s incredibly easy to hit the SOQL limits if your code will run in a very active organization. On a sandbox, you’ll probably never experience this while debugging or building the code.

Validation Rules are your friend. In the book “Clean Code”, Bob Martin was adamant about not repeating yourself and keeping things simple. By using validation rules we can keep our code clean and stop from repeating ourselves in multiple places. Validation Rules

Controllers should do the very minimum required to get a record, display a record, and save a record. If possible, pages should use standard controllers and then controller extensions to do any logic or processing. Anything else, should probably happen in a validation rule or a trigger. Unit Testing is vital because it’s impossible to test everything by hand, and Salesforce requires at least 75% code coverage across all classes and at least 1% code coverage for each trigger.

When developing custom logic for Salesforce, there’s no such thing as just a few minutes for development if a bug creeps in. Deploying code into production from a sandbox instance can take anywhere from half an hour to a few hours depending on the size of the codebase. Previously, I’ve done unit testing in .NET and in PHP and found it very helpful in reducing bugs. In Salesforce, the overall code coverage must be at least 75% for a deployment to be successful.

That’s a few things I’ve learned about Salesforce the hardway. What things have you learned since you started?

Introduction to Salesforce Workbench

Salesforce Logo

I recently found out about Workbench for Salesforce at Dreamforce. Workbench is a web based set of tools that’s designed for Salesforce Administrators and developers to interact with Salesforce.com using the Force.com APIs.

Using Workbench it’s pretty easy to view data, do data loading, perform SOQL queries or SOSL searches, etc.

After logging in successfully you can do a lot of operations. For example, querying standard and custom objects, doing inserts, upserts, updates, deletes, undeletes, purging, deploying, and etc. I’ve used it quite a bite for things I didn’t need or want to write code for.

Logging Into Salesforce Workbench

Logging into the Salesforce Workbench is pretty easy, it supports the username and password login. You’ll need to know which Environment to use, typically Production is your Production Org or your Developer Edition account.

Sandbox is likely everything else.

To login go to : https://workbench.developerforce.com/login.php.