Thursday, February 5, 2015

caused by: System.NullPointerException: Attempt to de-reference a null object


Below are few of the error which are encountered while working with soql and assigning values to variables.

There are situations when we need to check for null conditions. when we query  a sobject we must check the if the returened results are not null. Checking the null condition resolved many of the encountered errors. Lets see these with Examples
caused by: System.NullPointerException: Attempt to de-reference a null object

This Error is caused when there is no results in the query and the result is used which out checking the null condition.





Corrected Code-We need to add a check for null values to avoid this situation






System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.Name

This Error is caused by using the field which is not queried in soql query.


Corrected Code-We need to include all fields in soql query which is being in code.





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

This error is caused when the query cannot get the result back.



Corrected Code-we need to check the where clause to see if the variable is not null























Monday, January 26, 2015

Accessing Custom Settings in salesforce


Custom settings enables application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula fields, validation rules, Apex, and the SOAP API.

Using Custom Setting enables a developer to change the values in production without deploying the code again for the change in value.
Custom Settings can be used for URLS where URL may changes time to time and for the triggers which may have a requirement of deactivating and activating again.

How To Access Custom Settings

Methods used to get values-
  • getAll()
  • getValues(data_set_name)
  • getOrgDefaults()
  • getInstance(Profile_ID)



Step 1. Creating a custom setting and Custom field.





Step 2:- Click on Manage to insert data in custom setting. In this case we are adding custom URL which will be access by our code.





Step 3- Inserted Value in custom Setting.




Thursday, January 22, 2015

Emails From Salesforce

Sending Emails form salesforce-

There are different ways we can send Emails from salesforce-
Apex code-
You can use Apex to send individual and mass email. The email can include all standard email attributes (such as subject line and blind carbon copy address), use Salesforce email templates, and be in plain text or HTML format, or those generated by Visualforce.


Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'TestUser@test.com'};
String[] ccAddresses = new String[] {'TestUser@test.com'};

// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
// Specify the subject line for your email address.
mail.setSubject('Test Email');
// Specify the text content of the email.
mail.setPlainTextBody('This is Just a test Email');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });



Workflow Rule- In this way you need to create an Email template and the email can be sent to specified users based on some conditions specified on worflow rule.




Email Alert

From Records level- Clicking on an Email field on Records opens the outlook mails associated with salesforce and email can be sent to particular user.

Writing Test Classes in salesforce



Testing is an important part of the development process. Before you can deploy Apex or package it for the Force.com AppExchange, the following must be true.

·        
  • At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
  • Every trigger must have some test coverage.
  • All classes and triggers must compile successfully
Learning to write a Test class for Apex Code


Identify the operation on which a trigger is fired and Apex code is executed.In Test Class same scenario needs to be re-produced so that that trigger is fired and all possible conditions are checked in apex code.During a test call data is not written on salesforce database.



Step 1:- @isTest Annotation
This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3 MB for all Apex code

Step 2: Defining the Test Class

Step 3:-Defining the test Method.
This method is defined as a testMethod. This means that if any changes are made to the database, they are automatically rolled back when execution completes and you don't have to delete any test data created in the test method.



Example-

Trigger
trigger testTrigger on Cars (before insert,before update) {
List<Cars__c> Cr=[select id from cars where id=:Trigger.New];
List<Cars__c> updatecars=new List<Cars__c>
For(cars__C C:cr)
{
c.Price__c= c.Price__c-10000;
updatecars.add(c);
}
Update updatecars;
}

Test Class

@isTest ---------------Step 1
private class HelloWorldTestClass {--------------------step 2
    static testMethod void validateHelloWorld() {----------------step 3
       Cars__c c = new Cars__c(Name='BMW', Price__c=$100000);
       System.debug('Price before inserting new car: ' + c.Price__c);

       // Insert car
       insert c;
   
       // Retrieve the new car
       c = [SELECT Price__c FROM Car__c WHERE Id =:c.Id];
       System.debug('Price after trigger fired: ' + c.Price__c);

       // Test that the trigger correctly updated the price
       System.assertEquals(900000, c.Price__c);
    }
}


Wednesday, January 21, 2015

Salesforce Trigger Best Practices


System.LimitException: Too many SOQL queries: 101

Triggers are executed before or after records of a particular type are inserted, updated, or deleted from the Force.com platform database.

Before writing a trigger a requirement must be clear on which type of operation a trigger needs to run.

The following are the best practices with Example:

·  Minimizing  the number of data manipulation language (DML) operations by adding records to collections and performing DML operations against these collections.
·  Minimizing the number of SOQL statements by preprocessing records and generating sets, which can be placed in single SOQL statement used with the IN clause

Use of List ,Set and Maps helps avoiding governer Limit Exceptions.


The below code is not considered as a good code as it will eventually hit governor limits.

for (Account a : trigger.new) {
for (Contact c : [select id,otherphone from contact where accountid = :a.id]) {
c.OtherPhone= a.Phone;
update c;



Good practice using List,Maps and Sets.

Set<ID> ids = Trigger.newMap.keySet();
List<Account> Acc=[select id,otherphone from Account where id in :ids];
List<Contact> c=[select id,otherphone from contact where Accountid IN : Acc];
Map<id,Account> ContactMaps=new Map<Id,Account>();
List<contact>Updatecontact=new List<Contact>();
for(Account:Acc)
{
ContactMaps.put(Acc.id,Acc);

}

for(Contact con:c)
{
Con.OtherPhone=contactMaps.get(con.Accountid).phone;
Updatecontact.add(Con);

}
Update Updatecontact;

Salesforce WebService Using SOAP UI

Testing Salesforce Webservice through SOAP UI 


 Salesforce provides the ability to expose apex classes to external system through webservices.
 How to create a webservice class (Link to another Post)
Once we have created a webservice we need to test the web service through an external system. SOAP UI is a best tool to test any web service.


 STEP 1:- Generate an Enterprise WSDL from the salesforce org you want to test the web service. And Import the WSDL in SOAP UI.


STEP 2:-
Generate the WSDL for the web service class.And Import the WSDL in SOAP UI. Under different project Name.


STEP 3:-
In order to make a  web service call  from soap UI to Salesforce we need a session ID. We can get the session id by using the pre-defined Login Method.This method is available under SoapBinding tag for the project which we created while inporting Enterprise WSDL.





STEP 4:-

Getting Response for Login method and getting session ID. Delete the <soapenv:header> tag and provide the username and password in the request section. Press the Green button to make the request.Once the call succeeds we get the session Id which can be used in our web service call to test the webservice.


Image Missing

Response



In the same way we will be getting our response from the salesforce webservice class.



Monday, January 12, 2015

Salesforce 401 Developer Certification

Hello,
Today i Gave my Developer 401 Certification exam and thought I can share some of my experince with you all.
I am a salesforce developer since 4 years, never felt a need for certification.Last week i was tempted to do a certification just as a challenge and boom , that was it.
Being a salesforce developer i didnt felt the exam a tougher one but it was not easy too.
The exam is not a simple one if you dont have a hands on experince on salesforce.If you dont have a great experince on salesforce i suggest 3 weeks of study.
There were -60 multiple-choice questions, 90 min which is more than enough.
Study Guide-
There were no questions asking for the figures of any component available in salesforce(number of fields or relationships available).
Do not emphasis more on dump questions.Few questions form internet dumps matches but not the majority ones.Go through the salesforce org for each components.
Most of the questions are scenario based.
Understanding the question is most important.Take your time to understand the question.Mark the questions which you are not confident.you can get some hints for answers in questions ahead.
Please go through the fundamentals thoroughly-Fundamentals of salesforce-https://developer.salesforce.com/page/Force_Platform_Fundamentals
The Main areas of the questions are-
  • Security Settings
  • Field Level security- Most Importsnt
  • Junction Obeject
  • Master detail relationship
  • Reports- Gauge and metric, Tabular and summary.
  • Standard and Custom Controllers
  • workFlow rules and Approval processes
  • Currency fileds for the org
  • Formula fileds
  • encrypted fields
 All the best to all who are about ot get them certified.
 
 oIjFj