Tuesday 30 April 2013


Importing Data

In this section, you will import sample project and resource data into the Force.com database
using the Data Loader tool.This process is divided into three stages: preparing the
data, importing it, and then verifying it visually using the native user interface.This is certainly
not the only way to import data into Force.com, and probably not the easiest. But
it employs a free, widely used, fully supported tool from Salesforce that can scale up to
support large numbers of records and complex objects.

Data Preparation

Data Loader operates on CSV files.The first line of the file contains a header listing the
columns present in the data.The following lines are the body of the data, with each line a
record, values separated by commas.You should have access to Microsoft Excel or an
equivalent tool for working with CSV files.
To begin, export CSV files for the Project and Resource objects. Because no data exists
yet in the database, these files will be empty except for the header line.This serves as a template
for the import file, conforming the data to the layout expected by the Data Loader.

To export, perform the following steps:
1. Launch Data Loader. Click the Export button.
2. Enter your username and password and click the Log In button. Make sure your
password includes a Security Token appended to it. If you have not yet obtained a
Security Token, log in to Force.com using your Web browser, navigate to Setup ➝
My Personal Information ➝ Reset My Security Token, click the Reset Security
Token button, and get the Security Token from the email sent to you by
Force.com. Click the Next button when your login is completed.
3. Select the object to export, and click the Browse button to name the export file
and specify its directory. Name the file the same as the object name, and save it
where you’ll readily find it, such as the desktop.Then click the Next button.
4. Click the Select All Fields button.Then remove the system fields, which are ID,
OwnerId, IsDeleted, CreatedDate,CreatedById, LastModifiedDate, LastModified-
ById, and SystemModstamp. Click the Finish button.
5. Answer Yes to the confirmation dialog.The export is performed, and a summary
dialog is shown. Click the OK button to dismiss it.You now have a CSV file on
your desktop containing a single line with the names of the exported fields.

Friday 26 April 2013


On Salesforce Records

Every record has a Currency field that specifies the currency type for amounts in that record. All currency amounts display in the record’s currency and are also converted to the personal currency of the record owner, based on the conversion rates entered by your administrator. Amounts in the user’s personal currency are displayed in parentheses.
For example, if you do business with Acme, Inc., a German company, you can set the Currency field in the Acme, Inc. account to “EUR - Euro.” Amounts such as Annual Revenue will display in euros as well as in your personal currency.
You can set the Currency field for a record to any of your organization’s active currencies. If a particular currency is deactivated and it is already in use as a record currency, those records remain untouched. You cannot enter any new amounts using an
inactive currency

Scenario
The U.S. VP of Sales directs managers and salespeople in the U.S., Canada, and Mexico. Canadian managers and salespeople forecast and report in Canadian dollars, Mexican managers and salespeople in pesos. Users can also enter opportunities in any of the organization's active currencies (for example, Swedish krona). The U.S. VP of Sales can run reports to reconcile opportunities across the U.S., Canada, and Mexico and see these reports in U.S. dollars.
The European VP of Sales uses British pounds as her personal currency. She has sales managers in the UK, Germany, and Sweden. Salespeople are in these countries as well as in Norway and South Africa. Salespeople in the UK and South Africa report to the UK Sales Manager; Norwegian and Swedish salespeople report to the manager in Sweden. The European managers and salespeople all enter opportunities in their respective personal currencies; they can also use other active currencies as well (for example, Canadian dollars). The UK Sales Manager gets his salespeople's pound- and rand-denominated opportunities and forecasts rolled up to pounds. The sales manager in Sweden reports on her salespeople's krona- and euro-denominated opportunities using krona. Finally, the European VP of Sales gets all this data rolled up to pounds.
In Asia, the Japanese VP of Sales runs the entire division in yen, and has a sales manager in Singapore. The managers and salespeople create opportunities and run forecasts and reports in their local personal currencies. The Japanese VP of Sales has all of these roll up to Japanese yen.
The New York-based CEO has visibility into every division and runs reports denominated in U.S. dollars. If needed, he can drill down to see divisional forecasts or individual opportunities in the native currencies of those items.
Opportunities are typically managed within a country; however, there may be cross-country collaboration on deals. Eachopportunity has an associated record currency, determined by the Currency field of the opportunity. Opportunity amounts display in the record currency as well as the opportunity owner’s personal currency.

Thursday 25 April 2013


Multi Currency  In Sales force 

Salesforce is the only online CRM solution designed from the ground up to support global organizations. It provides advanced multi-currency support for Opportunity Management, Forecasting, and Reporting. Using this capability, each international division can track, forecast, and report on opportunities in local currencies, while providing company-wide reporting and forecasting in a single common currency.

Key Terms

Corporate Currency
The currency in which your organization’s corporate headquarters reports revenue. Serves as the basis for all currency conversion rates.
Conversion Rates
The currency conversion rates between the corporate currency and the multiple currencies used by your organization.Your organization’s administrator maintains these rates.
Personal Currency
A user’s default currency for quotas, certain forecasting versions, and reports. This must be one of the active currencies for your organization. If you use the Forecasts product released in Winter ‘12, your quota amounts display in your display currency.
Active Currency
A currency in which your organization does business. Only active currencies can be entered in opportunities, forecasts,and other items.
Inactive Currency
A currency that your organization no longer uses. You may have existing records that use inactive currencies, but you can’t enter new amounts using inactive currencies.
Record Currency
The default currency for a record. Every record has a Currency field that specifies the currency type for amounts in
that record.

Understanding Force.com Web Services
Force.com Web services allow data, logic, and metadata to be accessed from outside the
Force.com platform by any program that can communicate using SOAP messages over
HTTP.
Although the details of the Web services vary, the general procedure for writing a program
to invoke them remains constant.With a strongly typed language like Java or
C#.NET, stub code is generated from the Force.com WSDL.The program must log in to
Force.com to establish a session and can then invoke the Web service methods.
This section describes concepts that can be applied to using any Force.com Web service.
It consists of the following parts:
Basics of Force.com Web Services: Learn about the five Web services provided
by Force.com, how they are secured, and limits placed on their use.
Generating Stub Code:Walk through the process for generating Java or
C#.NET code from Force.com WSDL.
 Logging In: The first Web service call typically establishes a session with
Force.com by logging in.This session is used to make subsequent Web service calls
until it is invalidated explicitly or it expires.
 Force.com Data Types in SOAP: Understand how data types in Force.com
objects are expressed in Web services.
 Error Handling: Force.com Web services signal errors in a few ways, depending
on where the errors originate.

Understanding the Batchable Interface
To make your Apex code run as a batch you must sign a contract with the platform.This
contract takes the form of an interface called Batchable that must be implemented by
your code. It requires that you structure your processing logic into the following three
methods:
. start: The start method is concerned with the scope of work, the raw set of
records to be processed in the batch.When a batch is submitted to Salesforce for
processing, the first thing it does is invoke your start method.Your job here is to
return a QueryLocator or an Iterable that describes the scope of the batch job.
.execute: After calling the start method, Force.com has the means to access all
the records you’ve requested that it operate on. It then splits these records into sets
of up to 200 records and invokes your execute method repeatedly, once for each
set of records. At this point, your code can perform the substance of the batch operation,
typically inserting, updating, or deleting records. Each invocation of execute
is a separate transaction. If an uncaught exception is in a transaction, no further
transactions are processed and the entire batch job is stopped.
Caution
Transactions that complete successfully are never rolled back. So, an error in a transaction
stops the batch, but transactions executed up to that point remain in the database. Thinking
of an overall Batch Apex job as transactional is dangerous, because this is not its
default behavior. Additionally, you cannot use savepoints to achieve a single pseudo-transaction
across the entire batch job. If you must achieve job-wide rollback, this can be implemented
in the form of a compensating batch job that reverses the actions of the failed job.
n finish: The finish method is invoked once at the end of a batch job.The job
ends when all transactions in the scope have been processed successfully, or if processing
has failed. Regardless of success or failure, finish is called.There is no
requirement to do anything special in the method.You can leave the method body
empty if no post-processing is needed. It simply provides an opportunity for you to
receive a notification that processing is complete.You could use this information to
clean up any working state or notify the user via e-mail that his batch job is complete
and its outcome.

With this initial walkthrough of the Batchable interface, you can begin to apply it to
your own trigger or Visualforce controller code. If you find a process that is a candidate to
run as a batch, think about how it can be restructured to conform to this interface and
thus take advantage of Batch Apex.

 Dependent Fields: Dependent fields enable the standard “cascading picklist” user
 interface pattern, in which user selection in one picklist filters the available values
 in a second.
. Record Types: Record types allow records in a single object to take on multiple
personalities in the native user interface. For example, the standard object Account
is designed to store information on businesses, but with minor adjustments can support
data on individuals as well.This can be accomplished with record types.
.Roll-Up Summary Fields: Roll-up summary fields are like formula fields that
operate on a group of records, calculating their sum, minimum, maximum, or a
record count.
.Field History Tracking: Field History Tracking is an audit trail for your objects.
As records are updated, details of the changes are stored in a separate history object.
Details include the user modifying the record, the fields modified, and the old and
new values.
. Tags:Tags are an alternative way to search for records.They are user-created,
informal annotations of records that can be easily searched and shared to drive
collaboration.
. Force.com Connect Offline: This feature brings portions of your Force.com
database directly to your desktop.You can work disconnected from the Internet,
and your data is synchronized with Force.com when you reconnect.
. Custom Settings: Custom settings store and manage user preferences, aspects of an
application that can be configured by users rather than hard-coded by developers.
. Sample Application: Three of the preceding features are applied to enhance the
Services Manager sample application.

Aggregate SOQL Queries

SOQL statements that summarize or group records are called aggregate queries. Rather
than selecting a set of records and performing calculations on them in Apex, SOQL
allows you to do this within the database.This results in much better performance and
simpler code.This section covers three aspects of aggregate SOQL queries:

. Aggregate Functions: Rather than simply returning the discrete values of a database
field in a SELECT statement, aggregate functions such as SUM apply a simple
calculation on each record and return the accumulated result.

. Grouping Records: The GROUP BY syntax works with aggregate functions to
return a set of summarized results based on common values.

. Grouping Records with Subtotals: SOQL provides two special forms of the
GROUP BY syntax to calculate subtotals and return them in the query results.

Test your knowledge

  1. Out of the following things which can be done using the Force.com platform? (Select two)
    a. Data-warehousing
    b. Applications with clicks and not code
    c. Applications can be upgraded without loss of customization
    d. Code version control system
  2. Which of the following statements are true concerning e-mail activation? (Select one)
    a. The e-mail activation feature requires that the user click an activation link before logging in from a new computer
    b. The e-mail activation feature cannot be disabled
    c. The e-mail activation feature can be disabled by request to Salesforce.com support
    d. The e-mail activation feature can be disabled through the UI
  3. A security token is required for API access when connecting from an IP address within the list of trusted networks.
    a. True
    b. False
  4. Out of the following which applications are suitable for Force.com? (Choose three)
    a. Time card application
    b. Word processor
    c. Online auction management
    d. Inventory management
  5. Which of the following refers to the data model of Salesforce? (Choose 2)
    a. Force.com API
    b. Force.com metadata API
    c. Sandbox
    d. Force.com IDE
  6. What types of paid Salesforce edition are available?
    a. Enterprise edition
    b. Unlimited edition
    c. Trial edition
    d. Developer edition
  7. Where are Force.com IDs identical?
    a. Production and full copy sandbox only
    b. Production and dev sandbox only
    c. Two developer orgs
    d. Two sandbox org


Developer.Force.com

Along with a developer account, http://developer.Force.com provides additional resources for developers.


Authentication on Force.com

We can login to Force.com from any standard web browser or third-party application. Force.com uses a three-factor authentication method. From the browser, the user is authenticated using the username, password and the I.P. address of the system. The IP address where the account is created is automatically white-listed for the user.


Force.com application types

There are some common types of applications that are required to automate an enterprise process. They are as follows:
  • Content-centric applications: These applications enable organizations to share and version content across different levels. They consist of file sharing systems, versioning systems, and content management system.
  • Transaction centric applications: These applications focus on the transaction. They are applications such as banking systems, online payment systems, and so on.
  • Process centric applications: These applications focus on automating the business process in the organization such as a bug tracking system, procurement process, approval process, and so on. Force.com is suited to building these kinds of applications.
  • Data centric applications: These applications are built around a powerful database. Many of the organizations use spreadsheets for these applications. Some examples include CRM, HRM, and so on. Force.com is suited to building these kinds of applications.


The cloud computing model of Force.com

Force.com provides a 100 percent cloud computing model for enterprise application. The end-user does not have to worry about networks, hardware, software licenses, and so on. Everything is done on the cloud. The following features of Force.com make it a 100 percent cloud-based system:
  • Multi-tenant architecture: The multi-tenant architecture is a way of serving multiple clients on the single software instance. Each client gets their own full version of the software configuration and data. They cannot utilize the other instance resources. The software is virtually partitioned into different instances. The basic structure of the multi-tenant architecture is as shown in the following image:
    Just like tenants in a single building share the resources of electricity and water, the multi-tenant system shares common resources. Separate programs are written to ensure that a single instance does not monopolize the resources.
  • Automatic upgrades: The newer version of the application is released automatically with all the users. Any developments or customizations made during the previous version are automatically updated to the latest version without any manual modification to the code.
  • Subscription model: Force.com is distributed under the subscription model. The user can purchase a few licenses and build the system. After the system is up and successful, further user licenses can be purchased from Salesforce. This model ensures that there no large start-up fee and we pay as we go, which adds fixed, predictable costs in the future.
    The subscription model can be visualized like the electricity distribution system. We pay for whatever electricity we use and not the complete generator and the infrastructure.
  • Scalability: The multi-tenant kernel is already tested and running for many users simultaneously. If the organization is growing, there is always room for scaling the application with new users without worrying about the load balancing and data limitation. Force.com provides data storage per user, which means that the data storage increases with the number of users added to the organization.
  • Upgrades and maintenance : Force.com releases three updated versions every year. The new releases consist of feature updates to Salesforce.com and the Force.com platform with selected top ideas from IdeaExchange. IdeaExchange is the community of Salesforce users where the users submit ideas and the community votes for them. The most popular ideas are considered by Salesforce in their next release.

How to call  method from one salesforce account to another salesforce account


1.Create WSDL FOR class in which Methods is  there.
2. Create Apex class From that wsdl in to other Account
Create  class
global class CallCreatereservation {
public Static void  call(){
        //-----------------------------------
        // Login via SOAP/XML web service api
        //-----------------------------------
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        //not escaping username and password because we're setting those variables above
        //in other words, this line "trusts" the lines above
        //if username and password were sourced elsewhere, they'd need to be escaped below
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
          .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
          .getChildElement('result', 'urn:partner.soap.sforce.com');
        //-------------------------------
        // Grab session id and server url
        //--------------------------------
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();
System.debug('session id'+SESSION_ID );
System.debug('session url'+SERVER_URL );
soapSforceComSchemasClassGdGdxtran.SessionHeader_element obj1 =new soapSforceComSchemasClassGdGdxtran.SessionHeader_element();
obj1.sessionId=SESSION_ID;
soapSforceComSchemasClassGdGdxtran.GDXTransaction obj =new soapSforceComSchemasClassGdGdxtran.GDXTransaction();
obj.SessionHeader=obj1;
System.debug(obj.createReservation('Baljeet'));
}
  CallCreatereservation.call();

Wednesday 24 April 2013


Code To get Account Details From One Salesforce Account to other one



Visual Force Page 
<apex:page controller="FetchAccount" standardStylesheets="true">
<style type="text/css">
.errorMsg{
    font-size:0.8 em;
    color:red;
}
</style>
<apex:pageBlock >
<apex:form >
<apex:outputLabel value="UserName : " for="userName"/>
<apex:inputText required="true" id="userName" value="{!userName}" />
<br />
<apex:outputLabel value="Password : " for="pwd"/>
<apex:inputsecret id="pwd" value="{!pwd}"/>
<br />
<apex:commandButton id="getRecords" value="Get Records" action="{!fetch}" rerender="wrapper" status="waitStatus" />
<apex:actionStatus startText="Requesting..." stopText="" id="waitStatus"/>
<hr />
<apex:outputPanel id="wrapper">
<div class="errorMsg" style="display:{!displayError}"> {!errMsg} </div>
<apex:pageBlockTable value="{!acc}" var="account" id="accTable" rowClasses="odd,even" styleClass="tableClass">

    <apex:column >
        <apex:facet name="header">Account Name</apex:facet>
         <apex:outputText value="{!account.name}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Created By</apex:facet>
         <apex:outputText value="{!account.CreatedBy.FirstName}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Phone</apex:facet>
         <apex:outputText value="{!account.Phone}"/>
    </apex:column>

</apex:pageBlockTable>
</apex:outputPanel>
</apex:form>
</apex:pageBlock>
</apex:page>

Apex class
public with sharing class FetchAccount {

    //Login Domain May be test, prerellogin.pre
    String LOGIN_DOMAIN = 'www';
    public String pwd{get;set;}
    public String userName{get;set;}
    public List<Account> acc{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;}

    public FetchAccount()
    {
        displayError = 'none';
    }

    public void fetch()
    {
        errMsg  = 'Some error occurred, please try again';
        try
        {
        //-----------------------------------
        // Login via SOAP/XML web service api
        //-----------------------------------
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        //not escaping username and password because we're setting those variables above
        //in other words, this line "trusts" the lines above
        //if username and password were sourced elsewhere, they'd need to be escaped below
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
          .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
          .getChildElement('result', 'urn:partner.soap.sforce.com');

        //-------------------------------
        // Grab session id and server url
        //--------------------------------
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();

        //----------------------------------
        // Load first 10 accounts via REST API
        //---------------------------------
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.CreatedBy.FirstName, a.CreatedById From Account a limit 10');
        request = new HttpRequest();
        request.setEndpoint(theUrl.getUrl());
        request.setMethod('GET');
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);

        String body = (new Http()).send(request).getBody();

        JSONParser parser = JSON.createParser(body);

        do{
            parser.nextToken();
        }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));

        parser.nextToken();

        acc = (List<Account>) parser.readValueAs(List<Account>.class);
        }
        catch(Exception e)
        {
            displayError = 'block';
        }

    }
}