Sunday, April 20, 2014

Getting List of Objects from Apex

Situation:
In many scenarios, there is a requirement to retrieve a list of objects in an organization to process them. Apex has a class called Schema. It contains the entire schema of your organization. Objects, their fields, field type etc. can all be retrieved using this class.
This can be very useful. Suppose you want to create a dropdown menu and bind the list of objects in your organizations to it. You may also want to generate a list of fields when you select an object in the first dropdown.
Recipe:
The following code shows how to generate a list of objects:
<apex:page controller="objectList" >
  <apex:form >
    <apex:SelectList value="{!val}" size="1">
      <apex:selectOptions value="{!Name}"></apex:selectOptions>
    </apex:SelectList>
  </apex:form>
</apex:page>

The Visualforce page uses the following Apex class as its controller:

public class objectList{
  public String val {get;set;}
 
  public List<SelectOption> getName()
  {
    List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();     
    List<SelectOption> options = new List<SelectOption>();
    
    for(Schema.SObjectType f : gd)
    {
       options.add(new SelectOption(f.getDescribe().getLabel(),f.getDescribe().getLabel()));
    }
    return options;
   }
}

Findings:

  • This will generate all the objects in your organization. You can restrict them. For example if you want to retrieve only custom objects, you can place a check to ensure that only objects that contain '__c' should be added in the list.

Monday, April 7, 2014

Picking the right API

Salesforce provides programmatic access to your organization’s information using simple, powerful, and secure application programming interfaces.



When to Use REST API
REST API provides a powerful, convenient, and simple REST-based Web services interface for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web projects. However, if you have a large number of records to process, you may wish to use Bulk API, which is based on REST principles and optimized for large sets of data.

When to Use SOAP API

SOAP API provides a powerful, convenient, and simple SOAP-based Web services interface for interacting with Salesforce. You can use SOAP API to create, retrieve, update, or delete records. You can also use SOAP API to perform searches and much more. UseSOAP API in any language that supports Web services.
For example, you can use SOAP API to integrate Salesforce with your organization’s ERP and finance systems, deliver real-time sales and support information to company portals, and populate critical business systems with customer information.

When to Use Chatter REST API

Chatter REST API provides programmatic access to Chatter feeds and social data such as users, groups, followers, and files. UseChatter REST API to integrate Chatter into a variety of applications such as mobile applications, intranet sites, and third-party Web applications. Chatter REST API is similar to APIs offered by other companies with feeds, such as Facebook and Twitter.

When to Use Bulk API

Bulk API is based on REST principles and is optimized for loading or deleting large sets of data. You can use it to query, insert, update, upsert, or delete a large number of records asynchronously by submitting batches which are processed in the background by Salesforce.
SOAP API, in contrast, is optimized for real-time client applications that update small numbers of records at a time. Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands of records, it becomes less practical. Bulk API is designed to make it simple to process data from a few thousand to millions of records.
The easiest way to use Bulk API is to enable it for processing records in Data Loader using CSV files. This avoids the need to write your own client application.

When to Use Metadata API

Use Metadata API to retrieve, deploy, create, update, or delete customizations for your organization. The most common use is to migrate changes from a sandbox or testing organization to your production environment. Metadata API is intended for managing customizations and for building tools that can manage the metadata model, not the data itself.
The easiest way to access the functionality in Metadata API is to use the Force.com IDE or Force.com Migration Tool. These tools are built on top of Metadata API and use the standard Eclipse and Ant tools respectively to simplify the task of working with Metadata API. Built on the Eclipse platform, the Force.com IDE provides a comfortable environment for programmers familiar with integrated development environments, allowing you to code, compile, test, and deploy all from within the IDE itself. The Force.com Migration Tool is ideal if you want to use a script or a command-line utility for moving metadata between a local directory and a Salesforceorganization.

When to Use Streaming API

Use Streaming API to receive notifications for changes to data that match a SOQL query that you define.
Streaming API is useful when you want notifications to be pushed from the server to the client. Consider Streaming API for applications that poll frequently. Applications that have constant polling action against the Salesforce infrastructure, consuming unnecessary API call and processing time, would benefit from this API which reduces the number of requests that return no data.Streaming API is also ideal for applications that require general notification of data changes. This enables you to reduce the number of API calls and improve performance.

When to Use Apex REST API

Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.

When to Use Apex SOAP API

Use Apex SOAP API when you want to expose your Apex methods as SOAP Web service APIs so that external applications can access your code through SOAP. Apex SOAP API supports both OAuth 2.0 and Session ID for authorization.

When to Use Tooling API

Use Tooling API when you want to manage and deploy working copies of Apex classes and triggers and Visualforce pages and components, set checkpoints or heap dump markers, execute anonymous Apex, and access logging and code coverage information.

Sunday, March 30, 2014

Single Sign-On - Things to ponder

Consider the following when implementing Single Sign-On: 
  • Your organization’s implementation of the Web Service must be accessible by salesforce.com servers. Typically this means that you must deploy the Web Service on a server in your DMZ. Remember to use your server’s external DNS name when entering the Single Sign-On Gateway URL on the Company Information page within Salesforce.
  • If the Salesforce.com server cannot connect to your server, or the request takes longer than 4 seconds to process, the login attempt will fail. An error will be reported to the user indicating that his or her corporate authentication service is down.
  • Namespaces and element names are case sensitive in SOAP messages. Wherever possible, generate your server stub from the WSDL to ensure accuracy.
  • For security reasons, you should make your service available by SSL only. You must use an SSL certificate from a trusted provider, such as Verisign or Thawte.
  • sourceIp is the IP address that originated the login request. Use this information to restrict access based on the user’s location. Note that the Salesforce feature that validates login IP ranges continues to be in effect for Single Sign-On users.
  • You need a way to map your organization’s internal usernames and Salesforce usernames. If your organization does not follow a standard mapping, you may be able to extend your user database schema (for example, Active Directory) to include the Salesforce username as an attribute of a user account. Your authentication service can then use this attribute to map back to a user account. Alternatively, you can use a database to store the mapping of Salesforce username to your directory's username
  • Do not enable Single Sign-On for the system administrator’s profile. If your system administrators were Single Sign-On users and your Single Sign-On server had an outage, they would have no way to log in to Salesforce. System administrators should always be able to log in to Salesforce so they can disable Single Sign-On in the event of a problem.
  • We recommend that you use a Developer Edition account when developing a Single Sign-On solution before implementing it in your organization. To sign up for a free Developer Edition account, go to register or login.
  • Make sure to test your implementation with Salesforce clients such as Outlook Edition, Office Edition, and Offline Edition. 

Friday, January 17, 2014

Dealing Large Data and Salesforce


Best Practices

This section lists best practices for achieving good performance in deployments with large data volumes.

The main approaches to performance tuning in large Salesforce deployments rely on reducing the number of records that the system must process. If the number of retrieved records is sufficiently small, the platform might use standard database constructs like indexes or de-normalization to speed up the retrieval of data.

Approaches for reducing the number of records include:
  • Reducing scope by writing queries that are narrow or selective. 
For example, if the Account object contains accounts distributed evenly across all states, then a report that summarizes accounts by cities in a single state is much broader—and takes longer to execute—than a report that summarizes accounts by a single city in a single state.
  • Reducing the amount of data kept active
For example, if your volume of data is increasing, performance can degrade as time goes by. A policy of archiving or discarding data at the same rate at which it comes into the system can prevent this effect.

Scenario I:

Data Aggregation

Situation

The customer needed to aggregate monthly and yearly metrics using standard reports. The customer’s monthly and yearly details were stored in custom objects with four million and nine million records, respectively. The reports were aggregating across millions of records across the two objects, and performance was less than optimal.

Solution
The solution was to create an aggregation custom object that summarized the monthly and yearly values into the required format for the required reports. The reports were then executed from the aggregated custom object. The summarization object was populated using batch Apex.

Scenario II:

Custom Search Functionality

Situation

The customer needed to search in large data volumes across multiple objects using specific values and wildcards. The customer created a custom Visualforce page that would allow the user to enter 1–20 different fields, and then search using SOQL on those combinations of fields.

Search optimization became difficult because:
  • When many values were entered, the WHERE clause was large and difficult to tune. When wildcards were introduced, the queries took longer.
  • Querying across multiple objects was sometimes required to satisfy the overall search query. This practice resulted in multiple queries occurring, which extended the search.
  • SOQL is not always appropriate for all query types.

Solutions

The solutions were to:
  • Use only essential search fields to reduce the number of fields that could be searched. Restricting the number of simultaneous fields that could be used during a single search to the common use cases allowed Salesforce to tune with indexes.
  • De-normalize the data from the multiple objects into a single custom object to avoid having to make multiple querying calls.
  • Dynamically determine the use of SOQL or SOSL to perform the search based on both the number of fields searched and the types of values entered. For example, very specific values (i.e., no wild cards) used SOQL to query, which allowed indexes to enhance performance.

Tip: Searches that contain a leading wildcard are better performed by SOSL than SOQL.


Scenario III:

Indexing with Nulls


Situation

The customer needed to allow nulls in a field and be able to query against them. Because single-column indexes for picklists and foreign key fields exclude rows in which the index column is equal to null, an index could not have been used for the null queries.

Solution

The best practice would have been to not use null values initially. If you find yourself in a similar situation, use some other string, such as N/A, in place of NULL. If you cannot do that, possibly because records already exist in the object with null values, create a formula field that displays text for nulls, and then index that formula field.

For example, assume the Status field is indexed and contains nulls.

Issuing a SOQL query similar to the following prevents the index from being used.

SELECT Name
FROM Object
WHERE Status__c = ''

Instead, you can create a formula called Status_Value.

Status_Value__c = IF(ISBLANK(Status__c), "blank", Status__c)

This formula field can be indexed and used when you query for a null value.

SELECT Name
FROM Object
WHERE Status_Value__c = 'blank'

This concept can be extended to encompass multiple fields.

SELECT Name
FROM Object
WHERE Status_Value__c = '' OR Email = ''


Salesforce 1 | How to get started with Salesforce 1 platform Development

Salesforce have unveiled Salesforce 1, a new CRM platform to better connect with customers and to keep up with latest trends to reassure public that they are not falling behind. Seemingly there are lots of phenomena like Social, mobile applications, wearable devices and cloud computing,  so clearly business are looking for more tactical solution that meet the target implementations. Salesforce revamped the platform by consolidating all internet based technologies into one single service that companies can use to built out their offering and spend more time and focus on customer.
Salesforce 1, incorporates numerous API all into one platform with additional streaming API. Now most important things here to note is Salesforce is free for all user and even for developers free account. Clearly all the existing users will automatically be updated.

Design Your First Mobile Application 

Go to setup on your developer instance and type in 'Salesforce1' in quick search box and type in Salesforce 1 to make sure you have enable Salesforce1 instance as shown here



















To get started, you need a sample application and this application is pre-created by Salesforce to give you a vague idea of how the application is designed and can be used. Jump here to steps shown in this document in the link below

* These are steps mentioned over on  Salesforce 1 documentation  :

Install Salesforce 1 Application Package to Quick Start 


You might be familiar with the Warehouse app if you’ve gone through the tutorials in the Force.comWorkbook. We took the Warehouse data from that guide and added a few extra things to it to help show you what Salesforce1 can do.
  • Go to www.salesforce.com and log in to Salesforce using your Developer Edition credentials.
  • Open a new browser tab or window, and navigate to https://github.com/forcedotcom/Salesforce1-Dev-Guide-Setup-Package. Do this in the same browser that you used to log into your developer organization with.
  • Open the README file.
  • Click the bit.ly link in the README file. This is the installation link for the enhanced Warehouse data package. You should be taken directly into your development organization to the Package Installation Details page.
  • Click Continue.
  • Click Next.
  • Click Next.
  • Click Install.
  • Wait for the installation to finish.
  • From the Force.com app menu, select Warehouse.
  • Click the Data tab.
  • Click Create Data.
    All right! The last step is to download the Salesforce1 app, then we’ll be ready to roll.

    Download the Application for Apple/Andriod


    Now you need the device, I am here demonstrating through my iPhone, to get started you need to download the Salesforce1 Application from Apple stone through here

     

    Once you have download the application, you need to install the appplication on your device and login through your Salesforce Credentials like shown in my phone here






























    Pass on credential to login and select the warehouse application on the run and you will this confirmation message once you successfully install the application

    Enough of Administration now lets jump back to development and create a quick visualforce page to see how this work. Salesforce had provided some sample code with required static resource that you have already installed in the platform

    Create a Visualforce Page


    Now we’ll create a Visualforce page and make it available from the navigation menu.
    This Visualforce page references these items:
    • A static resource named googleMapsAPI
    • An Apex class named findNearby
      * Note this visualforce page comes in the package you have just installed 

      Make sure you have Mobile enabled on Visualforce Pages properties


      Open <sfintance>/apex//apex/FindNearbyWarehousesPage.

      Create a New VisualForce Tab

      To take this application to your Salesforce 1 Mobile Application, create a new Visualforce Tab.




      Add the Tab to the Navigation Menu

      Now let us add this tab to Mobile Navigation Menu

      Increase GeoLocation Miles to bring California for Multiple Pins

      N Since I am located in Austin, Texas so 2000 miles from here will bring California location in my Map, go to the FindNearby class and increase the radius



      Test Application on your Phone ! 





      Friday, October 11, 2013

      Salesforce CRM Content - Best Practices

      Salesforce Content Implementation approach/consideration:

      ·         Decide organization level access for your Salesforce CRM Content
      Each user must have a Salesforce CRM Content user license and plan had to be worked on for procuring the licenses, like number of licenses needed,
      permission for the specific users etc.,

      ·         List the number of libraries
      Review the files that are planned to be stored in Salesforce CRM Content and determine how many libraries needed and what
      content belongs to each library. Users are given access to content based on their library permissions.

      Note that every user has one personal library where he or she can store private or in-progress content.

      ·         Permissions needed for different libraries
      A library permission is a group of privileges assigned to each Salesforce CRM Content library member. It determines which
      tasks a member can perform in a particular library. The same user can have a different library permission in each of his or her
      libraries. All Salesforce CRM Content organizations include three library permissions by default: Viewer, Author, and
      Administrator. Customization on these library permissions or create new ones can be accomplished.

      Note that library permissions do not apply to personal libraries; all users can save content in their personal library

      ·         Decide on number of content types
      Content types are the containers for custom fields; they determine which fields are available during the publishing process
      and how the fields display on the content details page. You can create multiple content types and assign a content field to any
      or all content types.

      ·         Decide on custom fields requirement on the content
      All content types contain three default fields: Description, Tags, and Title.  Additional fields can be created and assign
      them to one or more content types.

      ·         Third party content integration requirement
      In Salesforce CRM Content, tags are descriptive labels that help classify and organize content. Contributors can assign tags
      to their files, content packs, Google docs, or Web links, thus enabling all library members to browse for content by tag. The
      tagging rule in a library determines how contributors can tag content; for example, the restricted-tagging rule does not allow
      contributors to create new tags. Library tagging rules are optional. By default, library contributors can enter any tag. The
      tagging rule options are open tagging, guided tagging, and restricted tagging.

      ·         Decide on content delivery
      A content delivery allows easily convert documents such as Microsoft PowerPoint and Word files into an optimized
      web-based version for easy online viewing. Once the delivery is decided, file’s encrypted URL can be sent to any recipient,
      such as leads, customers, partners, and colleagues, and then track how often the content is viewed or downloaded. In addition
      to tracking, content deliveries provide several benefits over sending files as attachments.

      ·         Multilingual support requirement
      Allow users to publish, edit, and search for content in any of the Salesforce-supported languages. Users can choose a
      language or publish in their personal language by default.

      ·         Requirement for enabling content for portal users

      Portal users with different levels of access to your Salesforce CRM Content organization can be setup.

      Friday, August 9, 2013

      SOQL Injection

      In other programming languages, the previous flaw is known as SQL injection. Apex does not use SQL, but uses its own database query language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks are much lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection. In summary SQL/SOQL injection involves taking user-supplied input and using those values in a dynamic SOQL query. If the input is not validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application into performing unintended commands

      SOQL Injection Vulnerability in Apex

      Below is a simple example of Apex and Visualforce code vulnerable to SOQL injection.
      <apex:page controller="SOQLController" >
          <apex:form>
              <apex:outputText value="Enter Name" />
              <apex:inputText value="{!name}" />
              <apex:commandButton value="Query" action="{!query}“ />
          </apex:form>
      </apex:page>
      
      public class SOQLController {
          public String name {
              get { return name;}
              set { name = value;}
          } 
          public PageReference query() {
              String qryString = 'SELECT Id FROM Contact WHERE ' +
                  '(IsDeleted = false and Name like \'%' + name + '%\')';
              queryResult = Database.query(qryString);
              return null;
          }
      }
      
      This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted. The user provides one input value called name. The value can be anything provided by the user and it is never validated. The SOQL query is built dynamically and then executed with the Database.query method. If the user provides a legitimate value, the statement executes as expected:
      // User supplied value: name = Bob 
      // Query string
      SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%')
      However, what if the user provides unexpected input, such as:
      // User supplied value for name: test%') OR (Name LIKE '
      In that case, the query string becomes:
      SELECT Id FROM Contact WHERE (IsDeleted = false AND Name LIKE '%test%') OR (Name LIKE '%')
      Now the results show all contacts, not just the non-deleted ones. A SOQL Injection flaw can be used to modify the intended logic of any vulnerable query.

      SOQL Injection Defenses

      To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables. The vulnerable example above can be re-written using static SOQL as follows:
      public class SOQLController { 
          public String name { 
              get { return name;} 
              set { name = value;} 
          } 
          public PageReference query() { 
              String queryName = '%' + name + '%';
              queryResult = [SELECT Id FROM Contact WHERE 
                 (IsDeleted = false and Name like :queryName)];
              return null; 
          } 
      } 
      
      If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands.

      For more information on SQL Injection attacks see: