Thursday, January 28, 2016

How to Enable Search Layout Section For Newly Created Objects in Salesforce

As we already know that once you have created any new custom object ,in the custom object detail page you will be seeing an section called Search Layout.But from Winter 16 releases for newly created objects you might not be able see the Search layouts section. because from winter 16 for newly created objects Search Layout Section will not be enabled automatically.Why is it?

Allow Search Feature 

1. Salesforce has introduced a new feature in winter 16 called "Allow Search "to disable or enable Search layout for a particular custom object

2.By using this feature you can improve the performance of global search/Side search by excluding unnecessary custom objects from search results

3.At the time of custom object creation you need to choose whether you want to enable or not.

4.If you want enable or disable follow below steps

  • Goto Setup--->Objects--->Custom Objects
  • Open the custom object for which you want to enable
  • Goto Search Status and select allow search to enable or deselect to disable
  • Go and observe the  Search Layouts section in object detail page 





Enjoy..........!




Monday, January 25, 2016

Compile Error: Incompatible key type Datetime for Map<String,List<Event>> at line

You will receive this type of error commonly when your working with collections or while doing at variable assignments .This error basically comes whenever your passing incorrect key datatype to maps.

1:  List<Event> eventRec= [Select StartDateTime,EndDateTime from Event limit 10];  
2:  Map<String,List<Event>> mapEvents = new Map<String,List<Event>>();  
3:  mapEvents.put( eventRec[1].StartDateTime,eventRec);  

In the above code snippet you will an error like Compile Error: Incompatible key type Datetime for Map&lt;String,List&lt;Event&gt;&gt; at line 3 column 1 because the mapEvents map key datatype is String but we are passing Datetime (eventRec.StartDateTime) type parameter. 

Wok Around Solution
Pass the correct key value datatype based on your map declaration.In our we need to pass so modified code as below
1:  List<Event> eventRec= [Select StartDateTime,EndDateTime from Event limit 10];  
2:  Map<String,List<Event>> mapEvents = new Map<String,List<Event>>();  
3:  mapEvents.put( String.valueOf(eventRec[1].StartDateTime),eventRec);  

Enjoy..........!!

Saturday, January 23, 2016

Rest API Errors in Salesforce



Below are the some of the errors we will receive while doing REST API integration

1.|FATAL_ERROR|System.JSONException: Can not deserialize SObject out of START_ARRAY token at [line:1, column:1]

2{"errorCode":"APEX_ERROR","message":"System.JSONException: Unexpected character ('C' (code 67)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]\n\n(System Code)\line 28, column 1"}

3.Malformed JSON: Expected '[' at the beginning of List/Set

4.Unexpected character ('C' (code 67)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]


Thursday, January 21, 2016

How to Highlight the selected row in a table in Salesforce Visual Force Page

If you are looking to highlight the selected row in a page block table in visualforce page.To do thos just add the below code snippet to your visualforce page to differentiate the selected row color among the rest of the rows/records in same page block table.

Visual Force Page:
<apex:page standardController="account" recordSetVar="accounts" sidebar="false" showHeader="false">  
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"/>  
<apex:stylesheet value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.css"/>  
   <script>  
     function highlightElem(elem){  
       $('tr').removeClass('ui-state-highlight');  
       $(elem).parent().addClass('ui-state-highlight');  
     }  
   </script>  
     <apex:form >  
       <apex:pageBlock >  
         <apex:pageBlockTable value="{!accounts}" var="a">  
           <apex:column value="{!a.name}" onclick="highlightElem(this)"/>  
            <apex:column value="{!a.BillingState}" onclick="highlightElem(this)"/>  
             <apex:column value="{!a.owner.name}" onclick="highlightElem(this)"/>  
         </apex:pageBlockTable>  
       </apex:pageBlock>  
     </apex:form>    
 </apex:page>  

OutPut:



Note:

1 . If you want to change the Highlighted color write your won style class and add that one script.

Enjoy....!!

How to get code coverage report class by class in Salesforce

Some times we will come across situation where we need to increase code coverage of 1% or 2% to get the 75% .To improve code coverage first we need to know the coverage report class by class but unfortunately in salesforce we don't have any option to get the report in single shot.To do this we have to navigate through the each and every class and we have to note down the coverage which is very headache thing and as well as time consuming process.

No worries,for every problem their would be a solution but only thing is that we need to explore for that one.To get the code coverage report class by class we can use ASIDE.IO. I would say Great thanks for the ASIDE.IO team because this is the number one tool to get the code coverage report class by class in salesforce with simple click only.Now I will explain how to use feature .

1. Login to ASIDE.IO as shown as below image by selecting type of the login



2.Once your login it will show your name Please verify whether you logged into correct instance or not and Click on < symbol to get more options


3.On click on < Symbol you will be getting more option as shown in below image.


4.Click on Test button to get more Unit Testing related options on left side as shown in below image


5.Click on Coverage Report button to get Click Here to Generate the Report option on Right Side


6. Click on the Generate the report button to download the coverage report in the form of .csv

    

7. Sample downloaded report looks likes as below image
  



8.Downloaded report contains below components we need to more concentrate on last 2 colums


  • Class Name,Coverage (%)
  • Total Lines
  • Lines Uncovered
  • Lines Covered
  • Remaining Coverage (%)
  • % Of Organization Total
  • Organization Potential Gain (%)

Hope this helps for everyone...Enjoy!!!

For more update please join this site or just like my Facebook page I Love Coding..You?


Tuesday, January 19, 2016

Error: entity is not org-accessible?

Basically we will be getting this error because of the many reasons among them here I'm listing few scenarios where we will be getting this one.

1. While deployment if your getting this means some features are enabled in source org and same has not been enabled in target org.
 
    Example: Enabled the Territories in Source Org and not in Target Org
    Solution : Enable Territories in Target Org also

2. While saving any Apex class/Trigger if your getting means you are using some feature which is not enabled currently in your org.

    Example : If your using OpportunityTeamMember object in Opportunity Trigger but in your organisation you haven't enabled the Opportunity Teams you will be receiving same error.
    Solution  : Enable Opportunity Team feature in your org first.

3. Any Spelling mistakes in API Names also causes same.

Enjoy.......!


Best Practices for writing Test Class in Salesforce

  • You must have at least 75% of your Apex covered by unit tests to deploy your code to production environments. In addition, all triggers must have some (at least 1%) test coverage.
  • We recommend that you have 100% of your code covered by unit tests, where possible.
  • Calls to System. Debug are not counted as part of Apex code coverage in unit tests.
  • Use Test.loadData () method to load test data from Static resources.
  • Use Test.starttest() and Test.starttest() to reset governor limits.
  • Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in any test method in the test class.
  • In the case of conditional logic (including ternary operators), execute each branch of code logic.
  • Make calls to methods using both valid and invalid inputs.
  • Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try…catch block.
  • Use Limits Class to avoid governor limits related issues.
  • Always handle all exceptions that are caught, instead of merely catching the exceptions.
  • Use System.assert methods to prove that code behaves properly.
  • Use the runAs method to test your application in different user contexts.
  • Use the isTest annotation. Classes defined with the isTest annotation do not count against your organization limit of 2 MB for all Apex code. See IsTest Annotation.
  • Exercise bulk trigger functionality—use at least 20 records in your tests.
  • Use the ORDER BY keywords to ensure that the records are returned in the expected order.
  • Not assume that record IDs are in sequential order.
  • Record IDs are not created in ascending order unless you insert multiple records with the same request. For example, if you create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID of account B may or may not be sequentially higher.
  • On the list of Apex classes, there is a Code Coverage column. If you click the coverage percent number, a page displays, highlighting all the lines of code for that class or trigger that are covered by tests in blue, as well as highlighting all the lines of code that are not covered by tests in red. It also lists how many times a particular line in the class or trigger was executed by the test
  • Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on.
  • Test the classes in your application individually. Never test your entire application in a single test.
  • Set up test data:
·         Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
·         Create all test data before calling the Test.starttest () method.
·         Since tests don't commit, you won't need to delete any data.
  • If you are running many tests, consider the following:
·         In the Force.com IDE, you may need to increase the Read timeout value for your Apex project. See https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse for details.
·         In the Salesforce user interface, you may need to test the classes in your organization individually, instead of trying to run all of the tests at the same time using the Run All Tests button.
·         Create Test Suites of Commonly Used Apex Test Classes Available only from Spring 16.

·         Check the disable parallel apex testing when your performing  Run All test

Changes to Developer Sandbox Licenses from Spring 16 Release

As we already know that number of the developer sandbox available in salesforce is depends on the Edition that you purchased.Before Spring 16 we have very less number of developer sandbox available for development.

As per the Spring 16 Release notes salesforce is going to increase the number of developer sandbox available in Enterprise,Unlimited and Performance Edition.You can now create more Developer sandboxes to develop, test, and deploy your custom apps. With more developer environments, you can reduce the time it takes to convert your ideas into apps.

Below table lists the changes to number of developer sandboxes available from spring'16.


                                                Developer Sandbox Licenses by Edition

Edition
Previous Number of Licenses
Licenses in Spring ’16
Enterprise Edition
1
25
Unlimited Edition
15
50
Performance Edition
30
100

Enjoy with new updates...!!

Aside.io for Salesforce

Aside.io is a Salesforce IDE ,up in the cloud ,which is built on top of the different API's like Metadata API and Tooling API .ASIDE is a free and full-featured Salesforce IDE built from the ground up for efficient delivery, design, and testing of Apex and Visualforce code.It's a very good tool to perform the Quick Development of code,Quick deployments,Running Test Classes and Performing the Queries.

Features:

1.CODE EDITOR:

  • Fast Saving the apex code without any dialog.
  • Rich User Interface with Auto complete features and highlighting the invisible characters.
  • Modifying the Static Resources directly in salesforce zip file without downloading.





















  • Run unit tests in three different ways: all at once, by query, or through individual selection.
  • View the Test classes results clearly with help of Stack Trace Parser.
  • Getting the code coverage report for all classes or set of classes.





















3.DEPLOY MANAGER:
  • Retrieving the components without building any package.xml.
  • Drag and Drop feature to Deploy or Retrieve the components from/into the salesforce.
  • Quick generation of the package.xml to share with others.





















4.QUERY TOOL:
  • Fetching the data from Standard Objects,Custom Objects,Custom Settings etc.
  • Export the query result as the form of CSV.
  • Easy way of Sharing the Query Results with others.
  • Quick Creation,Modifying or Deletion of the records.




















In my next post I will share How to use this Aside.io for development and deployments etc.


Keep watching the site for more updates enjoy......!

Monday, January 18, 2016

Settings and Uploading Custom metadata Records with Custom Metadata Loader in Salesforce

In my previous posts I have explained what is Custom MetaData Loader .Now I'm going to explain how to set up this tool/application in salesforce. If you're looking for how can we do the bulk deletion of the custom meta records you can refer the my latest post on "Bulk Delete The Custom Meta Data Records"

1. Download the Complete application Zip file from the git hub Source.

2. Deploy the Downloaded Zip file into your org using below tools
3. Once you have deployed the zip file successfully it will creates below components
  • 10 Apex Classes
  • 2  Apex Page
  • 1  Custom Application
  • 1  Custom meta data type
  • 1  Custom tab
  • 1  Permission Set
    For complete package.xml file you can refer here

4. Goto Setup-->Permission Sets-->Click on Custom Metadata loader-->Manage Assignments

5. Click on Add Assignments -->Add the users to whom you want to give access for this App.

6. Goto Application menu Select Custom Metadata Loader application.

7. Clicking on Custom Metadata Loader you will be receiving below error.




















8.To resolve that error we need to create a one Remote Site Setting. On clicking on the below Create Remote Site Setting button it will automatically creates a remote site setting directly.























9. Even after clicking the button your not able to create or if your getting error like Cannot create a new component with the namespace: srinu_dev_ed. Only components in the same namespace as the organization can be created through the API it means in your org you have enabled/created some custom domain.

10.To fix this issue 

  • In Classic : copy the complete page url where your receiving this error and goto Remote Site setting and give below details and save it.          

  • In Lightning : you cannot simply copy and paste the URL to the error page on the Custom Metadata Loader tab, you will need the VisualForce URL instead. Use https://________--c.visualforce.com where _____ is your custom domain, for example https://mydomain--c.visualforce.com  
        Remote Site Name : c_mdapi
        Remote Site URL         : Copied page URL
        Active                       : Checked

11. Now everything is finished on clicking on the Custom metadata loader you will receive the below screen.So you can start uploading the .csv file to insert the records.




























Note:
The .csv file header names must be the Api names of the Custom meta data type for auto mapping the fields.

Enjoy with Custom Metadata Loader....................!

Please comment or write us if you have any queries/requirements.

Please like,follow,bookmark,subscribe this site to receive daily updates.





Hope this helps you..Enjoy..!

Friday, January 8, 2016

Custom Metadata Loader in Salesforce

In my previous posts I have explained what is Custom MetaData Types and how to Create Custom Metadata Types in Salesforce. Once everything is set up next task is to create records in those custom metadata types.If it 10 to 15 records we can create manually but there are some situations where you need to load more number of records let take an example loading the country names and their respective country codes.

To do this there is no specific tools like Data loader and Import wizard in salesforce to upload Custom Metadata type records.To achieve this we have an other option called Custom Metadata Loader.

Custom Metadata Loader

  • Custom metadata loader is a tool for creating custom metadata records from a csv file. 
  • This Custom Metadata Loader is a custom application which build on top of the salesforce with the help of Metadata API to support bulk uploads.
  • Create custom metadata types in your Salesforce org using Metadata API and then use custom metadata loader to bulk load the records.
  • It supports up to 200 records upload with a single call.


In my next post I will post How to set up and how to upload the records with this tool in salesforce. 

Keep watching the site for more updates enjoy......!

Thursday, January 7, 2016

How to set Createddate Field value for Test Record in Salesforce Test class

(Note: The feature we are discussing here is as per the Salesforce Spring 16 preview release notes,So this feature is available from Spring 16 release of Salesforce, but features may or may not be available after the Spring 16 go to live )

Before Spring 16 if you are inserting let assume 20 test records in salesforce test class for all those 20 test records the created date is same .If you are working any scenario like to fetch only latest records 20 you will be getting all that 20 records with same created date because all records are inserted with same date so you can't guaranty that in which order they are coming even if you are using order by created date.

From Spring 16 release releasing this great feature to set the created date by the developer for the test records in salesforce test classes (It may or may not be released in Spring as per the note above).

The new Test class method called Test.setCreatedDate(RecordId,DateTime) which allows to set the created date for the test records in salesforce test class.

How to use:
1 . Create a test record in test class.
2.  Pass that record Id along with date time that you want set to Test.setCreatedDate(Id,DateTime).

 @isTest   
 private class SetCreatedDateTest {  
   static testMethod void testSetCreatedDate() {  
     Account a = new Account(name='Test Account');  
     insert a;  
     Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));  
     Test.startTest();  
     Account myAccount = [SELECT Id, Name, CreatedDate FROM Account   
                WHERE Name ='Test Account' limit 1];  
     System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));  
     Test.stopTest();  
   }  
 }  

Key points:
1.All database changes are rolled back at the end of a test. You can’t use this method on records that existed before your test executed.
2.You also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in your org.
3.This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.
4. You can see the doc related to this setCreatedDate at Reference Doc for SetCreatedDate.

I think now everyone is eagerly waiting for this new feature.Enjoy....!

Monday, January 4, 2016

System.QueryException: unexpected token: 'where'

Whenever you’re making any dynamic query construction in apex we will be ending with many errors .Among them one common error is System.QueryException: unexpected token: 'where' 

Code Snippet:
 String queryString = 'Select id,name,industry,';  
 queryString = queryString +'From Account';  
 System.debug('queryString ..'+queryString);  
 Database.query(queryString);  

When I run above code snippet I'm receiving System.QueryException: unexpected token: 'where' and then I checked my debug for the query it's something like as below

Debug value : Select id,name,industry, From Account

WorkAround 

 The extra comma in between Industry and From is causing the issue so if you remove that extra comma it will work perfectly.

Modified Code Snippet:
 String queryString = 'Select id,name,industry ';  
 queryString = queryString +'From Account';  
 System.debug('queryString ..'+queryString);  
 Database.query(queryString);  

So when ever your making dynamic quires please keep below points in mind

 1. Any extra commas are coming in queries
 2. Whether space is provided between last column and FROM statement
 3. Give space between From and Object Name

Got the solution....Enjoy..........!

How to create a Custom Metadata Types,Fields and Records in Salesforce

In my previous post I have written about Custom Metadata Types .In this post I'm going to explain how to create a Custom Metadata Types,Fields and Records.

Creating Custom Metadata Type:

1.Goto Setup-->Develop-->Custom Metadata Types

























2.Please fill all Label and Plural Label and also select the Visibility of Metadata Type




























3.Looks likes below image after filing all details for Protected Custom meta datatypes and click save

























4.After clicking it will be landed to Custom Meta data types details page which looks likes custom object detail page.Details page contains

  • Metadata type detail (All meta data type api names ends with  __mdt )
  • Standard Fields
  • Custom Fields (to create a user defined fields in Types)
  • Page Layouts       



























Creating Fields in Custom Metadata Type:

1.To create Custom fields click on new button on Custom fields section
2.Select field type and click on next
3..Here we need to fill all details and select the field Manageability as shown below


Creating Records in Custom Metadata Type:

1. Click on manage button to create a Record as shown below
 


2.Fill all field values and if you want to protect this record select protected component check box


























Enjoy with Custom meta data types.........!

Sunday, January 3, 2016

How to Restrict creation of Contact on Lead Conversion

Here I'm trying to avoid the creation of Contact on Lead conversion.Here the thing is that we can't stop the contact creation on lead conversion because it's standard process .So to achieve this we have an alternative solution is to delete the contact after the lead got converted.

To Delete I have a written a trigger on Lead like below

 trigger noContactOnLeadConversion on Lead (after update)   
 {  
  list<contact> conlead=new list<contact>();  
  for(lead leadRec:Trigger.new)  
  {  
   if(trigger.oldMap.get(leadRec.id)isconverted==false && leadRec.isconverted && leadRec.ConvertedContactId != null)  
   {  
       contact con= new contact(Id=leadRec.ConvertedContactId);  
       conlead.add(con);  
   }  
  }  
  delete conlead;  
 }  





















When I start converting the lead I'm ending up with an error System.DmlException: Delete failed. First exception on row 0 with id 0039000001pvmhtAAA; first error: ENTITY_IS_DELETED, entity is deleted: [] .





















Then I added the logic to stop recursion trigger and tried with before trigger also but still I'm getting the same error with different screen but error is same







WorkAround for the Error 

Move the deletion of contact part to the @future method(i.e.,Asynchronous execution )and use Boolean variable to stop Recursion trigger.Below is the modified code snippet.

Trigger code:
 trigger noContactOnLeadConversion on Lead (after update)   
 {  
 if(!LeadUpdateHandler.stopleadUpdateTrigger)  
 {  
  LeadUpdateHandler.stopleadUpdateTrigger= true;  
  list<contact> conlead=new list<contact>();  
  for(lead leadRec:Trigger.new)  
  {  
   if(trigger.oldMap.get(leadRec.id).isconverted==false && leadRec.isconverted && leadRec.ConvertedContactId != null)  
   {  
    contact con= new contact(Id=leadRec.ConvertedContactId);  
    conlead.add(con);  
   }  
  }  
  LeadUpdateHandler.AsyncExecution(JSON.serialize(conlead));  
  }  
 }  

Handler Class Code:
 global class LeadUpdateHandler  
 {  
   public static boolean stopleadUpdateTrigger = false;  
   @future  
   public static void AsyncExecution(String JsonStr)  
   {  
    List<Contact> conList = new List<Contact>();  
     conList = (List<Contact>)JSON.deserialize(JsonStr, List<Contact>.class);  
     delete conList;  
   }  
 }  

For more update please join this site or just like my Facebook page I Love Coding..You? 

Enjoy.....!

Custom Metadata Types in Salesforce

We can say that Custom Metadata Types are just like the List Custom Settings in Salesforce but only difference is that in Custom metadata types records are also treated as metadata(In custom settings records are treated as non metadata so you can't move custom settings records with the help of change sets) and the records,the Custom metadata types with protected feature and fields in it with manageable feature.

Custom metadata types are typically used to define application configurations that need to be migrated from one environment to another, or packaged and installed.

Usually we will be designing the apps with the help of data records in custom objects or custom settings.Now you can create custom metadata types and add metadata records,with all the manageability that comes with metadata is package,deploy,and upgrade.The most advantage is here is that querying custom metadata records doesn't count against SOQL limits.





















Filed Types Supported by Custom MetadataType
  • Checkbox
  • Date
  • Date and Time
  • Email
  • Number
  • Percent
  • Phone
  • Text
  • Text Area
  • URL
Custom metadata fields and their manageability:

   The developer of the Custom Meta Data type decides who can change the field values after they ate deployed to subscriber organization.

  • Locked after release: For any record of the type, the value of the field is immutable after deployment, even on the developer organization where the record was created.
  • Subscriber editable: Anyone with the correct permissions can change the value of the field at will. Any changes the developer deploys do not overwrite values in the subscriber's organization.
  • Upgradable: The developer of a record can change the value of the field by releasing a new version of the custom metadata package. The subscriber can’t change the value of the field.
Custom metadata records with protected feature:

   If a developer releases protected records in a managed package, access to them is limited in specific ways.

  • Code that’s in the same managed package as custom metadata records can read the records.
  • Code that’s in the same managed package as custom metadata types can read the records that belong to that type.
  • Code that’s in a managed package that doesn’t contain either the type or the protected record can’t read the protected records.
  • Code that the subscriber creates and code that’s in an unmanaged package can’t read the protected records.
  • The developer can modify protected records only with a package upgrade. The subscriber can’t read or modify protected records. The developer name of a protected record can’t be changed after release.
Notes:

1.A subscriber to a managed package containing a custom metadata type can’t add their own fields to that type. Only the org that develops the type can add custom fields to it.

2.If you create a protected custom metadata record in your organization, then it’s accessible only by your code, code from unmanaged packages, and code from the managed package that defines its type.

3.If you change a custom meta data type from protected to public, its protected records remain protected and all other records become public.

4.If you use Setup to create a new record on a protected type, the Protected Component checkbox is checked by default.

5.Once the custom metadata type is public, you can’t convert it to protected.

6.The subscriber can’t create records of a protected type.

For more info related this please go through this Link .

In next post I will cover how to create custom meta data types and what are the limits and limitations of Custom Metadata types.

Enjoy........!