Sunday 16 December 2012

Field expression not allowed for generic SObject.

Field expression not allowed for generic SObject : You cannot use direct reference or assignment when working with sObjects. Instead you must use their get and put methods.

So instead of
sObject s = [SELECT Id, Name FROM Account LIMIT 1];
// This is allowed
ID id = s.Id;
// The following lines result in errors when you try to save
String x = s.Name;
System.debug(id+' a ***** b '+x); 

you need to do:
sObject s = [SELECT Id, Name FROM Account LIMIT 1];
// This is allowed
ID id = s.Id;
// This is allowed
String x = String.valueOf( s.get('Name') );
System.debug(id+' a ***** b '+x);

Same applies to assigning values to sObjects. Instead of:
sObject s = [SELECT Id, Name FROM Account LIMIT 1];
// This is allowed
ID id = s.Id;
// The following lines result in errors when you try to save
s.Name = 'Test';
System.debug(id+' a ***** b '+x); 

you need to do:
sObject s = [SELECT Id, Name FROM Account LIMIT 1];
// This is allowed
ID id = s.Id;
// The following lines result in errors when you try to save
s.put('Name', 'Test'); 
System.debug(id+' a ***** b '+x); 

Monday 3 December 2012

Habits of Highly Efficient Visualforce Pages & Class

Habits of Highly Efficient Visualforce Pages & Class.

1) "Transcient" keyword to cut down view state

2) User Remoting to replace actionsupport, reduces view state and speed of return and allows for direct passing parameters, YOU are responsible for rerendering

3) Streaming API, actionPoller is crap

4) Asynchronous @future methods

5) Optimise SOQL queries (use limit, filter etc)

6) Standard Set Controllers

7) Limit data on the page, (135k viewstate, 15mb of markup)

8) Do not use salesforce resources (showheader false, standardstylesheets false)


Map of Id & List of An object for set Records of particular records.

Snippt of Code :

***********************************************************************

Map<Id, List < Temp__c > mapAccIdListTemp = new Map<Id, List<Temp__c>>();
List<Temp__c> listTemp = new List<Temp__c>();

for(Temp__c Temp : [SELECT Id, Account__c FROM Temp__c]){            
 if(mapAccIdListTemp.containsKey(Temp.Account__c)){
  listTemp = mapAccIdListTemp.get(Temp.Account__c);
 }
 else {
  listTemp = new List<Temp__c>();
 }
 listTemp.add(Temp);
 mapAccIdListTemp.put(Temp.Account__c, listTemp);
}

***********************************************************************


Thursday 29 November 2012

Solution for System.Exception: "DML currently not allowed"

Hi, Guys you can't execute DML in the Constructor (or execute a method containing DML from a Constructor) in the Apex Class. Like that :--

Scenario 1 :

*******************************************


{!acc}

*******************************************

public class testClass{
    public Account acc{get;set;} 
    //Constructor
    public testClass(){
        acc = [SELECT id, Name FROM Account WHERE Name = 'test1' LIMIT 1];
        acc.Name = 'test2';
        update acc;//DML
    }
}
*******************************************


Scenario 2 :

*******************************************


{!acc}

*******************************************

public class testClass{
    public Account acc{get;set;} 
    //Constructor
    public testClass(){
        updateAcc();    
    }
    public void updateAcc(){
        acc = [SELECT id, Name FROM Account WHERE Name = 'test1' LIMIT 1];
        acc.Name = 'test2';
        update acc;//DML
    }
}
*******************************************


Solution for System.Exception: DML currently not allowed :

1. if this is the controller for a VF page, you can use the "action" parameter on the page.
2. if this is the controller for a Component , you can use the "allowDML" parameter on the Component.

Thursday 25 October 2012

Critical Update - Generate correctly escaped markup

Prior to the Winter '13 release, text in some Visualforce pages and components might have been generated incorrectly. This markup could contain fragments that should have been escaped (for example, the "<" character generated as &'lt';) but were not. These fragments might be interpreted by the browser as markup rather than as text in the page. This problem has been corrected for all pages with API version 26.0 or later. Your organization might contain pages or components that depend on this incorrect processing. These pages need to be fixed. To fix them, you will generally need to use with the attribute escape="false" to cause the text to be generated unescaped, as it was previously.
If your page contains either:

<apex:outputText value="{!something}"/>, or
A free-standing expression {!something}

And you’re expecting the string returned by the controller for {!something} to be treated as markup, rather than displayed in the page, then this page needs to be changed.

For the first case, you need simply set the escape attribute to false, <apex:outputText value="{!something}" escape="false"/>.

For the second case, you need to modify the expression to be output using <apex:outputText> as with the first case:

<apex:outputText value="{!something}" escape="false"/>

When you have fixed any affected pages, you should activate this Critical Update.

VFP Page



  
  
  



class


global class criticalUpdate {

    public String dummyString
    { 
        get 
        {
            return '

Test

'; } set; } }

Saturday 20 October 2012

Testing Web Service Callouts

In Winter 13, Generated code is saved as an Apex class containing the methods you can invoke for calling the Web service. To deploy or package this Apex class and other accompanying code, 75% of the code must have test coverage, including the methods in the generated class. By default, test methods don’t support Web service callouts and tests that perform Web service callouts are skipped. To prevent tests from being skipped and to increase code coverage, Apex provides the built-in WebServiceMock interface and the Test.setMock method that you can use to receive fake responses in a test method.

Auto-generated apex class from WSDL


//Generated by wsdl2apex 
    

public class docSample {

    public class EchoStringResponse_element {

        public String EchoStringResult;

        private String[] EchoStringResult_type_info = new String[]{
                            'EchoStringResult',
                            'http://www.w3.org/2001/XMLSchema',
                            'string','0','1','false'};

        private String[] apex_schema_type_info = new String[]{
                            'http://doc.sample.com/docSample',
                            'true'};

        private String[] field_order_type_info = new String[]{
                            'EchoStringResult'};
    }

    public class DocSamplePort {

        public String endpoint_x = 'http://YourServer/YourService';

        private String[] ns_map_type_info = new String[]{
                             'http://doc.sample.com/docSample', 
                             'docSample'};

        public String EchoString(String input) {
            docSample.EchoString_element request_x = 
                               new docSample.EchoString_element();
            docSample.EchoStringResponse_element response_x;
            request_x.input = input;
            Map response_map_x = 
                      new Map();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
                 'urn:dotnet.callouttest.soap.sforce.com/EchoString',
                 'http://doc.sample.com/docSample',
                 'EchoString',
                 'http://doc.sample.com/docSample',
                 'EchoStringResponse',
                 'docSample.EchoStringResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.EchoStringResult;
        }
    }

    public class EchoString_element {

        public String input;
        private String[] input_type_info = new String[]{
                                 'input',
                                 'http://www.w3.org/2001/XMLSchema',
                                 'string','0','1','false'};
        private String[] apex_schema_type_info = new String[]{
                                 'http://doc.sample.com/docSample',
                                 'true'};
        private String[] field_order_type_info = new String[]{'input'};
    }
}


Web Service Callouts class

Class

public class WebSvcCallout {
    public static String callEchoString(String input) {
        docSample.DocSamplePort sample = new docSample.DocSamplePort();
        sample.endpoint_x = 'http://api.salesforce.com/foo/bar';
        
        // This invokes the EchoString method in the generated class 
    
        String echo = sample.EchoString(input);
        
        return echo;
    }   
}


First, implement the WebServiceMock interface and specify the fake response in the doInvoke method.

Test Class

@isTest
global class WebServiceMockImpl implements WebServiceMock {
   global void doInvoke(
           Object stub,
           Object request,
           Map response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
       docSample.EchoStringResponse_element respElement = new docSample.EchoStringResponse_element();
       respElement.EchoStringResult = 'Mock response';
       response.put('response_x', respElement); 
   }
}


Test class of Web Service Callouts class

Test Class

@isTest
private class WebSvcCalloutTest {
    @isTest static void testEchoString() {              
        // This causes a fake response to be generated 
    
        Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
        
        // Call the method that invokes a callout 
    
        String output = WebSvcCallout.callEchoString('Hello World!');
        
        // Verify that a fake result is returned 
    
        System.assertEquals('Mock response', output); 
    }
}

Thursday 20 September 2012

Unsupported parameter type in @future Method Using Trigger

Hi, Guys you can't pass Sobjects as parameters into asynchronous methods. "Methods with the future annotation cannot take sObjects or objects as arguments." You can pass a list or set of ID's and then query for the objects inside the method.

Trigger

trigger test on Book__c (before Update) {
    if(Trigger.isUpdate){
        LIST<String> myOldObjectststId = new LIST<String>();
        LIST<String> myNewObjectststId = new LIST<String>();
        
        Set<String> opportunitysalesids = new Set<String> ();        

        for (Book__c  b1 : [Select Id from Book__c where id in :Trigger.old]) { 
           myOldObjectststId.add(b1.id);         
        }
        for (Book__c  b2 : [Select Id from Book__c where id in :Trigger.new]) { 
           myNewObjectststId.add(b2.id);         
        }
        MyObjectUpdateAfter.testMethodFuture(myOldObjectststId ,myNewObjectststId );
    }
}


Class with Future Method

public class MyObjectUpdateAfter{
    @future
    public static void testMethodFuture(LIST<String> myOldObjectstst,LIST<String> myNewObjectstst){
        //Now use these Id of  myOldObjectstst & myNewObjectstst

    }
}

Winter '13 Force.com Platform Release Geolocation Custom Fields

The geolocation custom field allows you to create a field that identifies a location by its latitude and longitude. You can then use the geolocation field with the DISTANCE and GEOLOCATION formula functions to calculate distances between locations. For example, you can calculate the distance between two geolocation fields (such as between the warehouse and the store), or between a geolocation field and any fixed latitude-longitude coordinates (such as between the warehouse and 37.775°, –122.418°, also known as San Francisco).
Geolocation Field Limitations Geolocation is a compound field that counts toward your organization’s limits as three custom fields: one for latitude, one for longitude, and one for internal use. In this beta release, support for the compound field (geolocation) vs. the field’s components (latitude and longitude) varies depending on the functionality you’re using in Salesforce. For example, you can create list views that show the field and its components, but you can’t select the compound geolocation field in Apex; you can only run SOQL queries on a geolocation field’s components.

Other limitations of this geolocation beta release include:

1. History tracking is not available for geolocation fields.
2. Geolocation fields are not supported in custom settings.
3. Geolocation fields are not available in reports, dashboards, validation rules, Visual Workflow, or workflow and approvals.
5. Geolocation fields cannot be searched.
6. Geolocation fields are not available in Schema Builder.
7. DISTANCE and GEOLOCATION formula functions are available only when creating formula fields and in Visual Workflow.
8. Geolocation is supported in Apex only through SOQL queries, and only at the component level.


New in Winter '13 Release

Winter '13 Release on September 12, 2012


New in Winter '13 Release

1. Developer Console Enhancements: The Developer Console makes developing with Apex code even easier by adding tools for unit testing, querying and performing DML operations on your data. We'll also cover the new command line window and the flexibility to tailor the console layout.

2. Visualforce Enhancements: Visualforce charting is now generally available. In addition to being available to all Visualforce customers, charting features such as new chart types, control over color schemes, and enhanced rendering control.

3. Apex Code Enhancements: New interfaces to support testing callouts for both HTTP requests and for WSDL generated code, new string methods, additional JSON support, and non-primitive types in Map and Set keys.

4. The new Force.com Canvas: In pilot for Winter '13, the canvas framework allows for integration of third party applications within Force.com. Made up of a set of Javascript APIs, the Force.com Canvas allows for embedding of an app inside the Force.com UI and provides support for authentication between apps, cross-domain XHR, and the context about the environment in which the app is running.


Wednesday 19 September 2012

Throw the Exception in the Class

An exception is a special condition that changes the normal flow of program execution. That is, it's when something bad happens that the program can't deal with during execution. Exceptions are the language's way of throwing up its hands and saying, "I can't deal with this, you need to."
So what kinds of conditions can cause Apex to raise, or throw, an exception? Here are the most common examples:
1. Your code expects a value from something that is currently null
2. An insert or update statement fails to pass a custom validation rule you have set
3. Assigning a query that returns no records or more than one record to a singleton sObject variable
4. Accessing a list index that is out of bounds

In all these instances we're trying something that the language deems impossible, and an exception is thrown. Apex has 20 different kinds of exceptions--that's a lot of different kinds of exceptions, but since they're all subclassed from a generic exception class they are very similar to deal with. All the exceptions support standard methods for accessing the error message and the exception type.


Throw the Exception in the Class



public class ExceptionHandlingClass{}

try {
    // Your code here 
    
   throw new BaseException('This is Exception Handling');
} catch (Exception e) {  
    // This catches the Exception 
    
}
public class BaseException extends Exception {}

}

Friday 14 September 2012

Developer Console - Search text in Class Options

There are near X (cross for close ) , "Open in new window" component like this Sign (▲) click this & Simply Clicking (Ctrl +F) you can search anything in Class at Developer Console... There are given SnapShot :--


Thursday 13 September 2012

Difference b/w apex:actionFunction tag and JavaScript remoting

The apex:actionFunction tag:-
1. lets you specify rerender targets
2. submits the form
3. does not require you to write any JavaScript


JavaScript remoting:
1. lets you pass parameters
2. provides a callback
3. requires you to write some JavaScript


Wednesday 18 July 2012

PopUp Open & close Window

There are i Have created two pages two Solve PopUp Open & close Window


VFP Page 1 (Main Page)



    
    
        
    



VFP Page 2 (TEZ_VFP_OpenPopupPage )



    
    
        
    



Wednesday 11 July 2012

TESTING ApexPages.Message IN CONTROLLER

Class

public class SomeController { 
  public SomeController (ApexPages.StandardController controller) { 
    if (System.currentPageReference().getParameters(). 
        get(’someParam’)!= null { 
      ApexPages.addMessage(new ApexPages.Message 
          (ApexPages.Severity.CONFIRM, ‘Parameter Exists’)); 
    } else if (System.currentPageReference(). 
          getParameters().get(’update’)!= null) { 
      ApexPages.addMessage(new ApexPages.Message 
          (ApexPages.Severity.ERROR, 
         ’Parameter Does Not Exist’)); 
    } 
  } 
}


Test Class

@isTest
public class TestClass {
 static testMethod void testConstructorParameters_noParams() { 
    PageReference ref = 
        new PageReference(’/apex/yourVisualforcePage’); 
    Test.setCurrentPage(ref); 
    
    SomeController controller = new SomeController (null); 
        
    System.assert 
      (ApexPages.getMessages().size() == 1); 
    System.assert 
      (ApexPages.getMessages().get(0).getDetail() 
        == ‘Parameter Does Not Exist’); 
    System.assert 
      (ApexPages.getMessages().get(0).getSeverity() 
        == ApexPages.Severity.ERROR);    
  } 
  
  static testMethod void testConstructorParameters_paramExists() { 
    PageReference ref = 
        new PageReference(’/apex/yourVisualforcePage?someParam=xyz’);
    Test.setCurrentPage(ref); 
    
    SomeController controller = new SomeController (null); 
      
    System.assert 
      (ApexPages.getMessages().size() == 1); 
    System.assert 
      (ApexPages.getMessages().get(0).getDetail() 
        == ‘Parameter Exists’); 
    System.assert 
      (ApexPages.getMessages().get(0).getSeverity() 
        == ApexPages.Severity.CONFIRM);  
  }
}

Monday 9 July 2012

JavaScript Remoting Example

JavaScript remoting in Visualforce provides support for methods in Apex controllers to be called via JavaScript. This allows you to create pages with complex, dynamic behavior that isn’t possible with the standard Visualforce AJAX components. There are three aspects to JavaScript remoting:

1. The remote method invocation you add to the Visualforce page, written in JavaScript.

2. The remote method definition in your Apex controller class, written in Apex, but there are few differences from normal action methods.

3. The response handler callback function you add to or include in your Visualforce page, written in JavaScript.

VFP Page


    

    
    
    
    

Class


global class TEZ_AC_RemoteActionExample {
    //Variables
    public String accountName { get; set; }
    public static Account account { get; set; }
    
    // constructor
    public TEZ_AC_RemoteActionExample() { }  
    
    //Remote Action
    @RemoteAction
    global static Account getAccount(String accountName) {
        account = [SELECT Id, Name, Phone, Type, NumberOfEmployees FROM Account WHERE Name = :accountName];
        return account;
    }
}



Set remove(null) method throws an error

"System.NullPointerException: Argument 1 cannot be null" will be received :-- You can also Test by below example

Set <Integer> testSet = new Set <Integer>(); 
testSet.add(1); 
testSet.add(2);
testSet.add(null);  
testSet.add(3); 

testSet.remove(3);
testSet.remove(null);



Error is: "System.NullPointerException: Argument 1 cannot be null It is thrown by the line: testSet.remove(null)"

Wednesday 20 June 2012

How to pass 3 list values to new list?

I have three list with same size with values in it, i want to pass these three list values to new list

VFP Page


{!list1}
{!list2}
{!list3}
{!list4}


Class

public with sharing class TEZ_AC_listString{
    
    List list1 ;
    List list2 ;
    List list3 ;
    List list4 ;
    public List getList1() {
        list1 = new List();
        list1.add(string.valueof(1));
        list1.add(string.valueof(2));
        list1.add(string.valueof(3));
        list1.add(string.valueof(4));
        list1.add(string.valueof(5));
        return list1 ;
    }
    public List getList2() {
        list2 = new List();
        list2.add(string.valueof(11));
        list2.add(string.valueof(12));
        list2.add(string.valueof(13));
        list2.add(string.valueof(14));
        list2.add(string.valueof(15));
        return list2 ;
    }
    public List getList3() {
        list3 = new List();
        list3.add(string.valueof(21));
        list3.add(string.valueof(22));
        list3.add(string.valueof(23));
        list3.add(string.valueof(24));
        list3.add(string.valueof(25));
        return list3 ;
    }
    
    public List getList4() {
        list4 = new List();
        for(Integer i=0; i < list1.size() ;i++){
            String str = list1.get(i)+','+list2.get(i)+','+list3.get(i);
            list4.add(str);
        }
        return list4 ;
    }
}


Creating Tabs In VF Pages

VFP Page

<apex:page id="page" controller="TEZ_AC_pageblocktablecolumn" >
    <style>
        .activeTab 
        {
        background-color: #236FBD; color:white; 
        background-image:none
        }
        
        .inactiveTab 
        { 
        background-color: lightgrey; color:black; 
        background-image:none
        }
    </style>
    
    
    <apex:form id="frm" >
        <apex:tabPanel id="tabpanel1" switchType="client" selectedTab="name1" activeTabClass="activeTab" inactiveTabClass="inactiveTab" >
            <!-- Tab 1-->
            <apex:tab label="One" name="name1" id="tabOne">
                <apex:pageBlock id="pageblock" >
                    <apex:pageBlockTable id="pgtable" value="{!con}" var="cc" >
                        <apex:column value="{!cc.name}" />
                    </apex:pageBlockTable>
                </apex:pageBlock>
            </apex:tab>
            <!-- Tab 2-->
            <apex:tab label="Two" name="name2" id="tabTwo">
                <apex:pageBlock id="pageblock2" >
                    <apex:pageBlockTable id="pgtable" value="{!con}" var="cc" >
                        <apex:column value="{!cc.id}" />
                    </apex:pageBlockTable>
                </apex:pageBlock>
            </apex:tab>
            <!-- Tab 3-->
            <apex:tab label="Three" name="name3" id="tabThree">
                <apex:pageBlock id="pageblock3" >
                    <apex:pageBlockTable id="pgtable" value="{!con}" var="cc" >
                        <apex:column value="{!cc.name}" />
                    </apex:pageBlockTable>
                </apex:pageBlock>
            </apex:tab>
        </apex:tabPanel>
    </Apex:form>
</apex:page>

Class

public class TEZ_AC_pageblocktablecolumn{
    public list<contact> con{get;set;}
    public TEZ_AC_pageblocktablecolumn (){
        con=[select id, name from contact limit 1000];
    }
}

Wednesday 13 June 2012

OFFSET Added to SOQL

Use OFFSET to specify the starting row offset into a query’s result set. OFFSET is helpful for paging into large result sets and quickly jumping to a particular subset rows in large results. For example, the following SOQL query returns a result set that skips the first 100 rows of the full query results:

SELECT Name FROM Merchandise__c WHERE Price__c > 5.0 ORDER BY Name LIMIT 50 OFFSET 100

The resulting set of 50 records begins with the 101st record in the query result set.

Summer 12

New Release in Salesforce : Summer 12 Go through this link : http://developer.force.com/releases/release/Summer12

Wednesday 22 February 2012

What is salesforce.com ?

Salesforce.com is a global enterprise software company headquartered in San FranciscoCalifornia, United States. Best known for its Customer Relationship Management(CRM) product, through acquisitions Salesforce has expanded into the "social enterprise arena."