Wednesday, December 11, 2013

List of the Salesforce Object Key Prefixes


Key PrefixObject Type
000Empty Key
001Account
002Note
003Contact
005User
006Opportunity
007Activity
008OpportunityHistory
00BListView / View
00DOrganization
00EUserRole
00GGroup
00IPartner
Also OpportunityPartner, which "is automatically created when a Partner object is created for a partner relationship between an account and an opportunity"
00JOpportunityCompetitor
00KOpportunityContactRole
00NCustomFieldDefinition - Setup > Create > Objects > [Your Object] > [Your Field]
CF00NCustom Field Id using in the query string. Note the keyprefix isn't actually CF0. In this case "CF" has been appended to the "00N" of the Custom Field Definition.
00OReport
00PAttachment
00QLead
00SImportQueue
00TTask
00UEvent
00XEmailTemplate
00YEmailTemp
00aCaseComment or IdeaComment
Use caution as there are at least two object types exposed via the partner API with the same keyPrefix!
00aIdeaComment or CaseComment
Use caution as there are at least two object types exposed via the partner API with the same keyPrefix!
00bWebLink - Custom Button or Link
00cTraining
00eProfile
00hLayout - Page Layout
00iPricebook
00jProduct
00kOpportunityLineItem
00lFolder
00oOpportunityLineItemSchedule
Represents information about the quantity, revenue distribution, and delivery dates for a particular OpportunityLineItem.
Products, Price Books, and Schedules Overview
00pUserTeamMember
00qOpportunityTeamMember - "This object is available only in organizations that have enabled team selling."
00rAccountShare
00sAccountOwnerSharingRule
00tOpportunityShare
00uOpportunityOwnerSharingRule
00vCampaignMember
010CaseSolution
011GroupMember
012RecordType
013RecordTypePicklist
014ProfileRecordType
015Document
016BrandTemplate (Letterhead)
018EmailStatus
019BusinessProcess
01ABusinessProcessPicklist
01BLayoutSection
01CLayoutItem
01DUserAccountTeamMember
01GProfileLayout
01HMailmergeTemplate
01ICustom Object
01JPicklistMaster
01NScontrol
01PProfileTabConfiguration
01QWorkflowRule - AssignmentRule
01RRuleFilter
01SRuleFilterItem
01TRuleFilterAction
01UActionAssignEscalate
01VActionTask
01WActionEmail
01XActionEmailRecipient
01YCampaignMemberStatus
01ZDashboard
01aDashboardComponent
01bListViewCriterion
01cListViewDisplayColumn
01ePicklistSet
01hTranslation
01jLocalizedValue
01kFieldPermissions
01lActionResponse
01mBusinessHours
01nCaseShare
01oLeadShare
01pApexClass
01qApexTrigger
01rCustomTabDefinition - Visualforce Tab
01sPricebook2
01tProduct2
01uPricebookEntry
01vPricebookShare
01wOpportunityUpdateReminder
01yCaseOwnerSharingRule
01zCaseEscalation
020EventAttendee
022FiscalYearSettings
023Calendar
024CalendarShare
025ListLayoutItem
026Period
02ALeadOwnerSharingRule
02BLabelDefinition
02CLabelData
02DCaseHistory2
02FCustomFieldMap
02TCustomPage
02UCustomPageItem
02VPageComponent
02XCustomPageProfile
02YUserComponentData
02ZAccountContactRole
02aContractContactRole
02bComponentResourceLink
02cSharing Rule
02fDelegateGroup
02gDelegateGroupMember
02hDelegateGroupGrant
02iAsset
02kListLayout
02mCustomIndex
02nCategoryNode
02oCategoryData
02pDivTransferEvent
02qLayoutItemColumn
02rOpportunityAlert
02tEmailRoutingAddress
02uTabSet
02vTabSetMember
02wLoginIpRange
02xLoginHours
02yReportAggregate
02zReportColorRange
033AllPackage - Package being built in the developer org
034PackageMember
035SelfServiceUser
036JobQueue
037ReportColumn
038ReportFilterItem
039ReportBreak
03DContactOwnerSharingRule
03GAccountCriteriaSharingRule
03HContactCriteriaSharingRule
03ICaseCriteriaSharingRule
03JChatterMessage
03KChatterMessageThread
03MChatterConversation
03NChatterConversationMember
03aDependentPicklist
03cLayoutRightPanel
03dValidationFormula - Validation Rule
03eCustomSetupDefinition
03fCustomSetup
03gQueueSobject
03iConsoleConfig
03jCaseContactRole
03kConsoleConfigItem
03nApexClassIdentifier
03qApexClassIdentifierRelationship
03sContactShare
03uUserPreference
040ReportParam
043OutboundField
044ExternalizedReference
045PartnerNetworkSetup
04YActionFieldUpdate - Field Update
04ZEntityLock
04aProcessDefinition
04bProcessNode
04cProcessTransition
04dProcessTransitionCondition
04eProcessActionItem
04fProcessWorkitemProperties
04gProcessInstance
04hProcessInstanceStep
04iProcessInstanceWorkitem
04jProcessAllowedSubmitter
04kActionOutboundMessage - Outbound Message Id
04lOutboundMessage - Outbound Notification Id
04mAdditionalNumber
04nSoftphoneLayout
04oSoftphoneLayoutSection
04pSoftphoneLayoutItem
04qSoftphoneLayoutInfoField
04rSoftphoneLayoutCallType
04sAsyncRequest - AsyncResultDeployResult
04tAllPackageVersion - Install Package
04uActionOverride
04vCallCenter
04xPackageExtension
04zLayoutItemActionRef
050PackageLicense
051UserPackageLicense
052SfdcOutboundMessage
053WorkflowTimeTrigger
054WorkflowTimeAction
055WorkflowTimeQueue
056ContentTagName
057ContentDocumentSubscription
058ContentWorkspace
059ContentWorkspaceDoc
05AContentWorkspaceMembership
05BCampaignCriteriaSharingRule
05CContentVersionComment
05GIpWhitelist
05ICampaignSharingRuleFilterItem
05JContentVersionRating
05KContentVersionRenditionContent
05LDBCThumbnailFilter
05NContentVersionTagName
05PContentWorkspacePermission
05QContentTagSubscription
05RContentWorkspaceSubscription
05SContentUserSubscription
05TContentContent
05UEntityFeedLayout
05VContentNotification
05WContentNotificationParam
05XDocumentAttachmentMap
05ZContentWorkspaceRecentEvent
05tCustomEntityTranslation
060Portal
061PortalAccount
062PortalStyleConfig
063MobileConfig
064QuerySet
065QuerySetItem
066ApexPage
067PortalMember
068ContentVersion
069ContentDocument
06AContentDocumentLink
06BContentWorkspaceAllowedRecType
06GCustomConsoleComponent
06NApplicationDependency
06OServiceDeskAttributes
06PApplication - Connected App
070CustomReportType
071CrtObject
072CrtColumn - Related to reports in some way.
073CrtLayoutSection
076RateLimitingNotification
078ApiUsage
079MobileMarkedRecord
07AMassMail
07DFeedPostTemplate
07ESandbox
07FFeedFavorite
07GSummaryRecalcQueue
07JComponentObjectDependency
07KComponentFeatureDependency
07LApexLog
07MApexTestResult
07OCanvas
07PEntitySizeJob
07RDataCategoryMapping
07TAuthConfig
07UAuthConfigProviders
07VActionSend
07YBatchOrgSizeJob
07ZEntityDataSize
07eFeedPostTemplateItem
07nApexExecutionOverlayResult
080PacCrudPermission
081StaticResource
082UninstallExport - Data from Uninstalled Packages? A zip containing CSVs.
083Vote
084VoteConfig
085VoteStats
086MobileDevice
087Idea
08EAddressCountry
08FAddressState
08aCronJobDetail
08dCampaignOwnerSharingRule
08eCronTrigger
08gCronFiredTrigger
08sCampaignShare
090MobileExcludedField
091EmailServicesFunction
092Weekly Data Export
093EmailServicesAddress
094MobileView
095MobileViewSortColumn
096MobileViewDisplayColumn
097MobileViewFilter
099ApexComponent
09AFeedPollChoice
09BFeedPollVote
09DQuickActionDefinition
09FDatacloudPurchaseUsage
09HConnectedApplication2
09IQuickActionListItem
09JQuickActionList
09SAsyncRequestFFX
09TAsyncRequestFFXResult
09UDomainCookieStore
09VDashboardStickyFilter
09aCommunity
0A0ReportJob
0A1ReportJobFieldMap
0A2DevelopmentPackageVersion - Change Set
0A3InstalledPackageVersion - Installed Package
0A4ProcessTransitionApprover
0A5AllManagedPackageMember
0A7CustomShareRowCause
0A8ReportJobRun
0A9ReportJobRunError
0ABProfilePortalDelegate
0ADPackageEvent
0AHCompactLayout
0AIFirehoseCheckpoint
0ALExternalSocialAccount
0AMCompactLayoutItem
0ANCompactLayoutMapping
0ATEventLogFile
0AUAuthSecurityLevel
0AWCanvasFeedItem
0AXConsolePersonalization
0AZActionApex
0AfDeployRequest
0AiDeployMessage
0AjAsyncApiTransformationSpec
0AkAuthSession
0AlDeployTestResult
0B0MobileEntitySetting
0B1MessageIdentifier
0B2PortalLanguageConfig
0B3PortalLanguageTabConfig
0B9MobileTab
0BACustomDataType
0BBCustomDataTypeComponent
0BCCustomFieldDataColumn
0BEFileFieldData
0BFComponentAppVersion
0BGCampaignInfluenceAdjustment
0BHAllManagedClassRelationship
0BIContentVersionMap
0BJActionAssignTeam
0BLPackageIdMapping
0BMConnection - Salesforce to Salesforce
0BRLogSearchResult
0BVOpportunityCriteriaSharingRule
0BWMobilePushDevice
0BXHistoricalEntityConfig
0BYMqSlaRequest
0BZEmailBrand
0BaLoginBrandAsset
0BbLoginBrand
0BcMqSlaJob
0BdHistoricalFieldConfig
0BeHistoricalTransactionPrefix
0BfHistoricalStaging
0BiHistoricalSelectorValue
0BkHistoricalSelector
0BlBlacklistedConsumer
0C0Holiday
0C2MobileSession
0C8LongJob
0CCSiteChangelistComponent
0CFChatterNowUserFavorites
0CIEntityImplements
0CJFieldImplements
0CLSiteChangelist
0CSChatterNowUserSettings
0CiAppManifest
0D1DataCategoryGroup
0D2OrgWideEmailAddress
0D3OrgEmailAddressSecurity
0D4LeadCriteriaSharingRule
0D5FeedItem or NewsFeed or UserProfileFeed
Use caution as there are at least three object types exposed via the partner API with the same keyPrefix!
0D6FeedTrackedChange
0D7FeedComment
0D8AllManagedMemberOption
0D9LeadSharingRuleFilterItem
0DAEntityCategoryGroup
0DCProcessTransitionAction
0DDSynonymGroup
0DESynonym
0DFVersionSet
0DGNamedFilter
0DHFieldAttributes
0DMSite
0DNSitePageOverride
0DRAndroidPushApplicationSetup
0DSAppMenuItem
0DTIdeaReputationLevel
0DULimitUsageHistory
0DVPushUpgradeRequest
0DXPushUpgradeJob
0DYPushUpgradeJobError
0DbForecastingType
0DfInstanceSizeJob
0E0EmailSyncConfig
0E1EmailSyncEntitySetting
0E2EmailSyncFieldMapping
0E3EmailSyncValueMapping
0E4EmailConfigEntitySetting
0E5EmailUserEntitySetting
0E6EmailSyncAdvancedSetting
0E8EntitySubscription
0EAPackageVersionPatchOrg
0EBRenderer
0EGReportChart
0EHSummaryLayout
0EISummaryLayoutItem
0EJSummaryLayoutSliceInfo
0EMContentReference - Appears next to refid query string parameter when pulling images. See rtaimage servlet parameters…what does the refid refer to?
0EOPicklistItemProperty
0EPInbound Change Set?
0EQCategoryJobTask
0ERRichTextAreaFieldData
0EVAllInstalledPackageVersion
0EbModuleDependency
0EeHistoricalDataFilter
0EfHistoricalDataFilterItem
0EgGlobalDbKey
0F0EmailTempAttachmentMap
0F3ReportBlock
0F5PhotoItem
0F7FeedPost
0F8SoftphoneScreenPopOption
0F9CollaborationGroup
0FACsnDomain
0FBCollaborationGroupMember
0FGMobilePushServiceDevice
0FHLinkReference
0FMFeedMapping
0FOOrgSizeJob
0FPReportRunTracker
0FQTrialMaster
0FRPackageOperationError
0FTTopicAssignment
0FaContextFieldAttributes
0G1FeedFieldHistory
0G8ReportBucketField
0G9AccountSharingRuleFilterItem
0GCEmailDisclaimer
0GDReportBucketFieldValue
0GEReportBucketFieldSourceValue
0GHSchemaBuilderLayout
0GISchemaBuilderLayoutItem
0GJApplePushApplicationSetup
0H0SiteRedirectMapping
0H1CollaborationInvitation
0H4ConnectedApplication
0H7PackageSupportAccess
0HFPublishEvent
0HGEntitySharingModel
0HIReportBlockAggregate
0HNTwoFactorInfo
0HOMobilePushSetupRegistry
0HRMetricsTransmissionHistory
0HiAppIpRange
0HjAppManifestVersion
0HkConnectivityDevConfig
0HlConnectivityAttributes
0I0FeedLike
0I2SiteAsset
0I3SiteComponent
0I4Domain
0I5CollaborationGroupMemberRequest
0I6OpportunitySharingRuleFilterItem
0I7CaseSharingRuleFilterItem
0I8ContactSharingRuleFilterItem
0I9ReportObjectFilterItem
0IAKnowledgeLanguageConfig
0IBDashboardFilter
0ICDashboardFilterItem
0IDDashboardFilterRepCol
0IFPushTopic
0IIFeedCrossReference
0IOBrandingValue
0ISApexComponentAttribute
0IVLogSearch
0IXFieldSet
0IYFieldSetItem
0IhServiceDeskComponent
0IiPushProfileMapping
0IjPushIntent
0IkModule
0InPhoenixDataSync
0IoRawEmail
0J0SetupEntityAccess
0J2Personalization
0J4SPSamlAttributes
0J5PredictiveModel
0J8ServiceDeskHotkey
0JSJigsawSavedSearch
0JfDomainSite
0K0ActionKnowledgeSubmit
0K2ActionChatterPost
0K3ActionChatterPostRecipient
0LDRecalcCampaignStats
0LGReportInstance
0LNStorageSizeJob
0M1SocialUserAuth
0MESessionLevelPolicy
0MFSynonymDictionary
0MJSystemStreamingChannel
0O0XinstanceInfo
0P0FlowVariableAssignment
0P1Certificate
0P2CertificateIp
0PFParallelJobItemData
0PLPermissionSetLicense
0PQProcessTimeQueue
0PSPermissionSet - Permission set metadata
0PaPermissionSetAssignment
0Q0Quote
0QcActionQuickCreate
0RAActivityRelation
0REEventRelation
0RTTaskRelation
0SOAuthProvider
0TITopicIndex
0TOTopic
0TYTopicOntology
0TtTopicTerm
0XCExternalDataSource
0XUExternalDataUserAuth
0YaLoginHistory
0YmSetupAuditTrail
0YsParallelJobStatus
0YuIdpEventLog
0YwUserLogin
0caChatterActivity
0csOauthConsumerScope
0e1ProfileClientSettings
0ebEntityBlacklist
0hcHashtagCount
0hdHashtagDefinition
0htHashtag
0inInfluence
0nsProcessNodeSecurity
0rpRemoteProxy
0spServiceProvider
0tRTopicRecordSetting
0tSTopicSuggestionSetting
0teTopicUserEvent
0tgTopicGroupActivity
0trTrendingTopic
0tsProcessTransitionSecurity
0tuTopicUserActivity
100UserLicense
101ExternalString - Custom Label
102FeatureLicense
10yTaskRecurrenceException
10zEventRecurrenceException
110ObjectPermissions
111EventComments
112ProposedEventTime
113ProposedEventResponse
11aDBCThumbnail
1ciIntegration
1clChangeList
1dcMetadataContainer - from the Tooling AP
1deIDEWorkspace
1doApexExecutionOverlayAction
1dpIDEPerspective
1drContainerAsyncRequest - from the Tooling API
204SfdcPartner
2LAPermissionSetLicenseAssign
300InteractionDefinition
301InteractionDefinitionVersion
308InteractionCondition
309InteractionOperand
30AInteractionAllocator
30CInteractionChoice
30DInteractionDecision
30FInteractionForm
30LInteractionConnector
30QInteractionQuestion
30RInteractionReference
30SInteractionStatement
30VInteractionVariable
30aInteractionAllocation
30cInteractionConstant
30dInteractionDataColumn
30fInteractionFormula
30gInteractionLayoutGroup
30mInteractionApexCall
30rInteractionResource
30tInteractionTodo
30vInteractionValueList
310InteractionLayoutDetail
31ASubinteraction
31CSubinteractionVariableAssignment
31SInteractionSwitch
31VInteractionFieldValue
31cInteractionChoiceLookup
31dInteractionDataSource
31iInteractionDataInput
31oInteractionDataOutput
31vInteractionValueListEntry
3M1OrgObjectsMetrics
3M3ChatterMetrics
3M4ChatterOrgWideMetrics
3M5NetworkCustomerLoginMetrics
3M6NetworkPartnerLoginMetrics
3MAPermissionSetMetricsByOrg
3MCOpportunityMetrics
3MDContentMetrics
3MFSharingRowCauseMetrics
3MGSharingMetrics
3MHIdeaMetrics
3MIUserDimMetrics
3MJPermissionSetLicenseMetrics
400ApexClassMember
401ApexTriggerMember
402ApexPageMember
403ApexComponentMember
4A0MetadataCheckout
4F0ApexClassVersion
4F1ApexTriggerVersion
4F2ApexPageVersion
4F3ApexComponentVersion
500Case
501Solution
5SpSegmentSpace
608ForecastShare
6AAAssociationQueueItem
6ABEventAssociationItem
6ACMailAssociationItem
6ADTaskAssociationItem
701Campaign
707AsyncApexJob
708BatchApexRelationship
709ApexTestQueueItem
710LoginIp
711ApiLoginKey
712LoginIpEmail
713ClientBrowser
714ApexCodeCoverage
715ApexCodeCoverageAggregate
716ApexOrgWideCoverage
729Photo
737FieldHistory
750AsyncApiJob - Bulk Query Job
751AsyncApiBatch - Bulk Query Batch
752AsyncApiQueryResult - Bulk Query Result
753TempStore
754AsyncApiJobOptions
766UiStyleDefinition
777UiStyle
7tfTraceFlag
800Contract
806Approval
80DOrganizationValue
888OauthConsumer - Remote Access

System.Exception: SObject row does not allow errors

Scenario:
 Error: System.Exception: SObject row does not allow errors
  
   This Exception is thrown when your adding an error message to particular record in a list which is looping through For Loop and that list gets records from the Trigger.oldMap context variable in Trigger.You can you use the addError method for only those records that are available in Trigger Context. 

Trigger Example:

 trigger BeforeDeleteConatct on Contact (Before Delete)
{
 Set<Id> conSet=Trigger.OldMap.keyset();
 List<Contact> listCon=[select id,phone from contact where id in:conset];

 for(Contact c:listCon)
 {
  if(c.Phone!=null)
  {
    System.debug('.......c......'+c);
    c.addError('you cant delete this contact because  it conatins Phone Number');
   }
  }
}

When you click on delete button of a particular contact it throws below error

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger BeforeDeleteConatct caused an unexpected exception, contact your administrator: BeforeDeleteConatct: execution of BeforeDelete caused by: System.FinalException: SObject row does not allow errors: Trigger.BeforeDeleteConatct: line 11, column 1". 
Work Around to Resolve This Error:

 trigger BeforeDeleteConatct on Contact (Before Delete)
{
 Set<Id> conSet=Trigger.OldMap.keyset();
 List<Contact> listCon=[select id,phone from contact where id in:conset];

 for(Contact c:listCon)
 {
  if(c.Phone!=null)
  {
    System.debug('.......c......'+c);
    Add below line of code to resolve Error
    Contact actualRecord = Trigger.oldMap.get(c.Id);
    actualRecord.addError('you cant delete this contact bcz it conatins Phone Number');
   }
  }
}

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "you can't delete this contact because it conatins Phone Number".

Test Class for Before Trigger in Salesforce

Test Class:

    In the previous post I have posted one Before Trigger .For that Trigger the test class is given Below.

Test Class Code:

  @IsTest
private class Account_Trigger_Test 
{
	private static testMethod void testDelete()
	{
           Account acc=new Account(Name='Test Account;);
           insert acc;
 
           // should succeed
           delete acc;
        }

	private static testMethod void testDeleteFail()
	{
           Account acc=new Account(Name='Test Account',
                                   Client_ID__c='Should fail');
           insert acc;
 
           try
           {
              delete acc;
              // should throw an exception - the following assertion will cause an error if the code carries on
              System.assert(false);
           }
           catch (DMLException e)
           {
               // expected - could assert the message here
           }
        }
}

Before Delete Trigger in Salesforce

Scenario:
    
  Write a Trigger on Account Object, All it does is to prevent Delete of an Account if a particular field(i.e.,Client_ID__c) not Null.

Trigger Code:

  trigger CannotDeleteAccountWithClientID on Account (before delete) 
 { 
  if(System.Trigger.IsDelete)
   { 
    for (Account Accts : trigger.old) 
    {
      if (Accts.Client_ID__c != null)
 Accts.addError('You cannot delete an Account Please contact your Salesforce.com Administrator for assistance.');
        }
    } 
   }
 }

Notes:

Trigger.oldReturns a list of the old versions of the sObject records.Note that this sObject list is only available in update and delete triggers.
Trigger.isDeleteReturns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.

Monday, December 2, 2013

Five things to do while writing an apex code to prevent pulling your hair out later.

Monday, Dec 2, 2013

A new intern joined the team excited to learn about Salesforce. She had a little Java background and thought that Salesforce was very easy compared to Java. In her eagerness, she wrote a 20 lines of code to prove her skills and grasp on Salesforce. The problem was, the code could be written in just 3 lines.

When you are coding on Salesforce, you have to keep in mind the following things:

 
 
 
 
 
                                                                                                                          i) If you can save some lines of code, save it, you can use those lines later. 
If you can write a code in 5 lines, don't waste a 6th one. That one line you saved could be the difference between spending a weekend in office optimizing the code or going to a party at the weekend.

ii) Write like the code will run forever.
Yes, your Sales team has taken in writing that there will only be three records in the system. Yes, you have written a good code for that. But when you are dealing with Salesforce, remember that data is going to increase over a period of time. Today you may be processing a 100 records but there will be a time when you might have to process 1000 or 100000. That period might be beyond your warranty support but it is going to come. You cannot write a prophecy about the day your code broke. Bulkify your code to handle as much data as you can. Put a check if the data is beyond your limit and print a decent, good error message for the future developer to understand what is wrong.

iii) Dread the governor limits
You may hate them, you may love them but you cannot ignore them. Salesforce governor limits are the harsh reality of this world, just like it will rain when you forget your raincoat at home. The governor limit are going to show their face just when you are about to close your day. Write a code to avoid the limits. Have you heard of a developer who wrote such an efficient code that no Governor limit was broken? Neither have I. But you can try to be as close as possible to the legend.

iv) SOQL/DML should not be allowed to enter a FOR loop
This rule is Salesforce 101. No DML or SOQL statement should be inside for loop, even if you are running the loop for only two records.

  1. for(Contact c: ContactList){
  2. //THIS IS A NO NO NO
  3. account a = [Select id,name from Account where id=:c.accountid];
  4. c.name=c.name+a.name;
  5. //THIS IS A EVEN BIGGER NO
  6. update c;
  7. }

The code written above is a recipe for disaster. Instead the same code can be optimized as:

  1. for(Contact c: ContactList){
  2. accountSet.add(c.accountid);
  3. }
  4. //Whuuu huuu not inside any loop
  5. Map<id,Account> accountMap = new Map<id,Account>([Select id,name from Account where id=: accountSet]);
  6. for(Contact c: ContactList){
  7. //Like they say in treasure hunt movies, a map comes in handy.
  8. c.name=c.name+ accountMap.get(c.accountid).name;
  9. }
  10. update ContactList;

v) Use Collections Set, Map wherever possible
If in your code you have to loop inside a loop, make sure to use a map instead of a list for the inner loop. When we use a map, it is easier to fetch data and will save you a lot of time. Using map also helps speed up the code.

  1. for(Contact c: ContactList){
  2. for(account a: accountList){
  3. if(c.accountid==a.id){
  4. //do something awesome
  5. }
  6. }
  7. }

This code is good enough but can be optimized even more like this

  1. for(Contact c: ContactList){
  2. if(c.accountid==accountMap.get(c.accountid)){
  3. //do something awesome
  4. }
  5. }

These are five simple things can will make your life easier. Being a Salesforce developer is a great honor, use it wisely. Use it fairly.

Friday, November 29, 2013

Test Class Example For Messaging.IndboundEmail Class

Apex Class:

 global class inBoundEmail implements Messaging.InboundEmailHandler
{
   global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,                 Messaging.InboundEnvelope envelope)
   {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        String subToCompare = 'Create Contact';

       if(email.subject.equalsIgnoreCase(subToCompare))
        {
            Contact c = new Contact();
            c.Email=email.fromAddress;
           
            // capture phone number and city also from incoming email.
            // Splits each line by the terminating newline character
            // and looks for the position of the phone number and city
            String[] emailBody = email.plainTextBody.split('\n', 0);
            c.LastName=emailBody[0].substring(0);
            c.Phone = emailBody[1].substring(0);
            c.Title = emailBody[2].substring(0);
                     
            insert c;
           
            // Save attachments, if any
            if (email.textAttachments != null)
            {
            for(Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments)
            {
            Attachment attachment = new Attachment();

            attachment.Name = tAttachment.fileName;
            attachment.Body = Blob.valueOf(tAttachment.body);
            attachment.ParentId = c.Id;
            insert attachment;
            }
           
            }

            //Save any Binary Attachment
           
            if (email.binaryAttachments != null)
            {
            for(Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
            Attachment attachment = new Attachment();

            attachment.Name = bAttachment.fileName;
            attachment.Body = bAttachment.body;
            attachment.ParentId = c.Id;
            insert attachment;
            }
           }
        }

        result.success = true;
        return result;
           
   }
}

Test Class For Above Class:

   @isTest(seeAllData=true);
Private Class InBoundEmailTest()
{
//Test Method for main class
     static testMethod void TestinBoundEmail()
    {
       Test.startTest();
      // create a new email and envelope object
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
     
       // setup the data for the email
      email.subject = 'Create Contact';
      email.fromAddress = 'someaddress@email.com';
      email.plainTextBody = 'email body\n2225256325\nTitle';
     
      // add an Binary attachment

      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfileone.txt';
      attachment.mimeTypeSubType = 'text/plain';
      email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };

 
      // add an Text atatchment
 
      Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
      attachmenttext.body = 'my attachment text';
      attachmenttext.fileName = 'textfiletwo3.txt';
      attachmenttext.mimeTypeSubType = 'texttwo/plain';
      email.textAttachments =   new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
     
     
      // call the email service class and test it with the data in the testMethod
      inBoundEmail  testInbound=new inBoundEmail ();
      testInbound.handleInboundEmail(email, env);
       

   }
}

Thursday, November 21, 2013

Like Operator in SOQL Query

Like Operator:

        Like Operator in SOQL act as a Comparison operator  for String Field Expression.Expression is true if the value in the specified fieldName matches the characters of the text string in the specified value. It provides a mechanism for matching partial text strings and includes support for wildcards.


Notes:

  • The % and _ wildcards are supported for the LIKE operator.
  • The % wildcard matches zero or more characters.
  • The _ wildcard matches exactly one character.
  • The text string in the specified value must be enclosed in single quotes.
  • The LIKE operator is supported for string fields only.
  • The LIKE operator performs a case-insensitive match, unlike the case-sensitive matching in SQL.
  • The LIKE operator in SOQL and SOSL supports escaping of special characters % or _.
  • Do not use the backslash character in a search except to escape a special character.
Special Characters % and _

   %-->Specifies that Zero ,One or more characters 
   _ --> Specifies that only One character.

SOQL Query Examples for Like Operator

Example, the following query matches Appleton, Apple, and Bappl , but not Appl:

   SELECT Id, Name FROM Widget__c WHERE Name LIKE 'appl_%'

Example 1:Withou Using Variable

     1.[Select Id,FirstName form User where FirstName LIKE 'srinivas'];

     2.[Select Id,FirstName form User where FirstName LIKE '%srinivas'];

     3.[Select Id,FirstName form User where FirstName LIKE '%srinivas_'];

Example 2:Like Using Variable need to use (:) bind Variavble

    User object contains FirstName as below Records:
     1. srinivasa
     2. msrinivasa
     3. srinivas

   String firstname ='srinivas';

 User u=  [SELECT Id , FirstName,LastName  FROM User where FirstName LIKE : firstName LIMIT 9];

  This query returns Users record from User object where FirstName of user is srinivas only.
  output: srinivas record only number3

Example 2:Using variable with % and _ wildcard characters
  String firstname ='srinivas';
  String str='%'+firstname +'%';
 User u=  [SELECT Id , FirstName,LastName  FROM User where FirstName LIKE : firstName LIMIT 9];

This query will return Users record from User object where FirstName of User contains srinivas
output:It returns Three Records  1. srinivasa 2. msrinivasa 3. srinivas

                              
                                                         
                               


Thursday, October 24, 2013

Working with Custom SOAP and REST Services in .NET Applications

           The Force.com platform gives developers a multitude of choices for accessing data. The SOAP API and REST API provide complete access to standard and custom Force.com objects. However, the need often arises to extend built-in functionality in order to support unique business requirements. Fortunately for Force.com developers, it's simple to create powerful, custom services that can be consumed in any platform.
This article explains how developers can build custom Force.com SOAP and REST services and consume them in .NET applications.

         For More information please Click Here.

Friday, October 11, 2013

Editing Multiple Records at a Time using the RecordSetVar

Scenario:

         You want to edit multiple records at a time ,Don't worry .Salesforce also provided Standard List Controllers(RecordSetVar) along with Standard ,Custom and Extension Controllers.By using RecordSetVar we can achieve it.

  RecordSetVar:
       This attribute indicates that the page uses a set-oriented standard controller. The value of the attribute indicates the name of the set of records passed to the page. This record set can be used in expressions to return values for display on the page or to perform actions on the set of records. For example, if your page is using the standard accounts controller, and recordSetVar is set to "accounts". 

Standard list controllers can be used with the following objects:
  • Account
  • Asset
  • Campaign
  • Case
  • Contact
  • Contract
  • Idea
  • Lead
  • Opportunity
  • Order
  • Product2
  • Solution
  • User
  • Custom objects

VisualForce Page:
<apex:page standardController="Opportunity" 
           recordSetVar="opportunities"
           tabStyle="Opportunity" sidebar="false">
  <apex:form >
    <apex:pageBlock >
      <apex:pageMessages />
      <apex:pageBlockButtons >
        <apex:commandButton value="Save" 
                            action="{!save}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockTable value="{!opportunities}" 
                           var="opp">
        <apex:column HeaderValue="Oppty Name">
          <apex:inputField value="{!opp.name}"/> 
        </apex:column>
        
        <apex:column headerValue="Stage">
          <apex:inputField value="{!opp.stageName}"/>
        </apex:column>
        <apex:column headerValue="Close Date">
          <apex:inputField value="{!opp.closeDate}"/>
        </apex:column>
      </apex:pageBlockTable>      
    </apex:pageBlock>
  </apex:form>
</apex:page>
 
Note:
    By default the RecordSetVar only displays 20 records at a time.If you want change 
the number of records displayed you can use the extension controller to set the size.
 
ScreenShots: 

Before changing the AB oppty stage from NeedAnalysis to ProposalPriceQuote


After changing the AB oppty stage from NeedAnalysis to ProposalPriceQuote

 






Monday, September 30, 2013

Submit a Form with the Enter Key


Problem

You've created a form in Visualforce. When pushing enter while using the form, the page refreshes instead of submitting your form. It's an easy fix with a small bit of JavaScript, which does wonders for your app's user experience.

Solution

In your Visualforce page, define this JavaScript function. It intercepts key presses on your form elements.

01<script type='text/javascript'>
02    function noenter(ev)  {
03        if (window.event && window.event.keyCode == 13 || ev.which == 13) {
04            doSearchAF();
05            return false;
06         } else {
07              return true;
08         }
09     }
10</script>           

Also, define this ActionFunction and tie it to your submit method in your controller.

1<apex:actionFunction name='doSearchAF' action='{!doSearch}' />

Lastly, this 'onkeypress' event should be added to every textual form element that should intercept a press of the enter key.

1<apex:inputtext value='{!settings.searchStr}' id='searchStr' styleclass='searchStr' onkeypress='return noenter(event);' />

Discussion

Make sure the ActionFunction name matches up with the JavaScript function you're calling from noEnter(). When someone hits Enter, the noEnter() JavaScript function will get called, which in turn will call the doSearchAF ActionFunction, which invokes your forms submit action, in this case doSearch().

How to Hide the Current Date Link on an Inputfield

Problem

The standard apex:inputfield component for a date field generates a link next to the input field, taking a lot of space. The link allows someone to easily enter the current date. However, when you use multiple date fields within a table component, it can be confusing for the user to have these extra links (see Screenshots). This recipe solves this by creating a Visualforce component that uses CSS to remove the link.

Screenshots

Default Behavior: Current date link is rendered

Note the extra links next to each and every date field.
 Modified Behavior: Using a Visualforce component to remove the current date link

As you can see, this is a much more compact view.

Visualforce Component Code

Here's the code for the Visualforce component. It wraps the component body in an HTML div tag, and adds styling to hide a part of that wrapped component.

 <apex:component access="global">  
   <style>  
     div.hideCurrDate span.dateInput span.dateFormat{  
     display:none;  
     }  
   </style>  
   <div class="hideCurrDate">  
   <apex:componentBody />  
    </div>  
 </apex:component>  

How to use the component

Here's a simple Visualforce page to demonstrate component usage:

 <apex:page standardController="Opportunity">  
    <apex:form>  
    <apex:pageBlock>  
     <apex:pageBlockSection>  
     <c:noDateLink>  
      <apex:inputField value="{!Opportunity.CloseDate}"/>  
     <c:noDateLink>  
     </apex:pageBlockSection>  
    </apex:pageBlock>  
    </apex:form>  
  </apex:page>  

Discussion
This code is dependent on the standard salesforce look and feel - and in particular dependent on it not changing. By examining the standard CSS, we know that the current date link is in a span.dateInput span.dateFormat CSS element. So this may be a little fickle depending on UI changes - but it should be easy to change if the standard UI CSS does ever change.

Enjoy.....!!

Friday, September 27, 2013

Most Important OnLine Tool for Coding and Decoding(i.e.,For Conversion)

Coder's Tool Box:

The Coder’s Toolbox contains all the little tools you never know where to find.
  • Time conversion – convert between Unix timestamp, ISO8601 and RFC 2822 formats
  • String conversion – encode/decode Base64-encoding; escape XML, URL's and ECMAScript; translate to UTF-8
  • Number conversion – convert between decimal, hexadecimal, octal and binary numbers
  • Network – calculate netmasks, broadcast addresses and do DNS lookups
  • Bandwidth – calculate the duration of file transfer
  • XPath debugger – test your XPath expressions
For more information please visit the below link

http://coderstoolbox.net/string/#!encoding=base64&action=encode&charset=iso_8859_1

Displaying Selected Records Below With Help of Action Support Function

Scenario:
       I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.


VisualForce Page:

<apex:page controller="wrapperClassController">
  <apex:form >
    <apex:pageBlock >
      <!-- In our table we are displaying the cContact records -->
      <apex:pageBlockTable value="{!contacts}" var="c" >
         <apex:column >
            <apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
              <!-- This is our selected Boolean property in our wrapper class -->
                <apex:inputCheckbox value="{!c.selected}" />
            </apex:actionSupport>
         </apex:column>
         <!-- This is how we access the contact values within our cContact container/wrapper -->
         <apex:column value="{!c.con.Name}" />
         <apex:column value="{!c.con.Email}" />
         <apex:column value="{!c.con.Phone}" />
       </apex:pageBlockTable>

    </apex:pageBlock>
      <apex:pageBlock id="test">
        <apex:outputPanel id="pbt2">
          Total No of Selected Records :<apex:outputText value="{!value }"/>
          <apex:pageBlockTable value="{!SelectedContacts}" var="c" >
             <apex:column value="{!c.Name}" />
             <apex:column value="{!c.Email}" />
             <apex:column value="{!c.Phone}" />
          </apex:pageBlockTable>
        </apex:outputPanel>
      </apex:pageBlock>
    </apex:form>
</apex:page>

Controller Class:

public class wrapperClassController
{
 //Our collection of the class/wrapper objects cContact
 public List<cContact> contactList {get; set;}
 public List<Contact> selectedContacts{get;set;}
 public Integer value {get;set;}

 public List<cContact> getContacts()

 {
  if(contactList == null) {
   contactList = new List<cContact>();
   for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
   {
     //As each contact is processed we create a new cContact object and add it to the contactList
     contactList.add(new cContact(c));
   }
  }
  return contactList;
 } 

 public PageReference processSelected()
 {
   //We create a new list of Contacts that we be populated only with Contacts if they are selected
   selectedContacts = new List<Contact>();

   //We will cycle through our list of cContacts and will check to see if the selected
   //property is set to true, if it is we add the Contact to the selectedContacts list


   for(cContact cCon : getContacts())
    {
      if(cCon.selected == true)
      {
       selectedContacts.add(cCon.con);
      }
    }
   value = selectedContacts.size();
   System.debug('printing listcontc'+selectedContacts.size());

   // Now we have our list of selected contacts and can perform any type of logic we want,
   // sending emails, updating a field on the Contact, etc

   return null;
 }
   
 //This is our wrapper/container class. A container class is a class,a data structure,or an
 //abstract data type whose instances are collections of other objects. In this example a
 //wrapper class contains both the standard salesforce object Contact and a Boolean value


 public class cContact
 {
  public Contact con {get; set;}
  public Boolean selected {get; set;}

  //This is the contructor method. When we create a new cContact object we pass a Contact
  //that is set to the con property. We also set the selected value to false

  public cContact(Contact c)
      {
            con = c;
            selected = false;
        }
    }
}

ScreenShot:



Displaying Selected Records Below With Help of Action Support Function

Scenario:
       I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.


VisualForce Page:

<apex:page controller="wrapperClassController">
  <apex:form >
    <apex:pageBlock >
      <!-- In our table we are displaying the cContact records -->
      <apex:pageBlockTable value="{!contacts}" var="c" >
         <apex:column >
            <apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
              <!-- This is our selected Boolean property in our wrapper class -->
                <apex:inputCheckbox value="{!c.selected}" />
            </apex:actionSupport>
         </apex:column>
         <!-- This is how we access the contact values within our cContact container/wrapper -->
         <apex:column value="{!c.con.Name}" />
         <apex:column value="{!c.con.Email}" />
         <apex:column value="{!c.con.Phone}" />
       </apex:pageBlockTable>

    </apex:pageBlock>
      <apex:pageBlock id="test">
        <apex:outputPanel id="pbt2">
          Total No of Selected Records :<apex:outputText value="{!value }"/>
          <apex:pageBlockTable value="{!SelectedContacts}" var="c" >
             <apex:column value="{!c.Name}" />
             <apex:column value="{!c.Email}" />
             <apex:column value="{!c.Phone}" />
          </apex:pageBlockTable>
        </apex:outputPanel>
      </apex:pageBlock>
    </apex:form>
</apex:page>

Controller Class:

public class wrapperClassController
{
 //Our collection of the class/wrapper objects cContact
 public List<cContact> contactList {get; set;}
 public List<Contact> selectedContacts{get;set;}
 public Integer value {get;set;}

 public List<cContact> getContacts()

 {
  if(contactList == null) {
   contactList = new List<cContact>();
   for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
   {
     //As each contact is processed we create a new cContact object and add it to the contactList
     contactList.add(new cContact(c));
   }
  }
  return contactList;
 } 

 public PageReference processSelected()
 {
   //We create a new list of Contacts that we be populated only with Contacts if they are selected
   selectedContacts = new List<Contact>();

   //We will cycle through our list of cContacts and will check to see if the selected
   //property is set to true, if it is we add the Contact to the selectedContacts list


   for(cContact cCon : getContacts())
    {
      if(cCon.selected == true)
      {
       selectedContacts.add(cCon.con);
      }
    }
   value = selectedContacts.size();
   System.debug('printing listcontc'+selectedContacts.size());

   // Now we have our list of selected contacts and can perform any type of logic we want,
   // sending emails, updating a field on the Contact, etc

   return null;
 }
   
 public List<Contact> getSelectedContacts()
 {
  System.debug('printing listcontc inside get'+selectedContacts.size());
  if(selectedContacts.size()>0)
     return selectedContacts;
  else return null;
 }

 //This is our wrapper/container class. A container class is a class,a data structure,or an
 //abstract data type whose instances are collections of other objects. In this example a
 //wrapper class contains both the standard salesforce object Contact and a Boolean value


 public class cContact
 {
  public Contact con {get; set;}
  public Boolean selected {get; set;}

  //This is the contructor method. When we create a new cContact object we pass a Contact
  //that is set to the con property. We also set the selected value to false

  public cContact(Contact c)
      {
            con = c;
            selected = false;
        }
    }
}

ScreenShot: