Ajax (1) Apex Class (12) Apex Trigger (2) Community (2) Home Page (1) HTML (4) Integration (3) JS (7) KB (1) Label (1) Licenses (1) Listing (1) Log (1) OOPs (5) Sharing (1) Static Resource (1) Test Class (3) URI (1) Visualforce (10)

Friday 27 June 2014

Share a case using trigger

Note:
Default access lavel
trigger trgsharingTest on Case (after insert, after update) {
    if(trigger.isAfter==true && (trigger.isInsert==true||trigger.isUpdate==true) && trigger.new.size()>0 && trigger.new!=null)
    {
      List<CaseShare> lstShare=new List<CaseShare>();
        
        for(Case obj:trigger.new )
        {
           CaseShare objShare=new CaseShare();
              objShare.CaseAccessLevel='Edit';
              objShare.CaseId=obj.id;
              objShare.UserOrGroupId='005i00000038RVcAAM';
              lstShare.add(objShare);
        }
        //Database.SaveResult[] jobShareInsertResult = Database.insert(lstShare,false);
        
        insert lstShare;
    }
}

Thursday 26 June 2014

jquery Field Updation

<apex:page standardController="Opportunity" id="Lpti_New_Opportunity">
<apex:includeScript value="{!URLFOR($Resource.JQuery, 'jquery1.9.1.min.js')}"/>
<script>
    $(document).ready(function(){
    
    StageChangeEvent();
    $('[Id$=iptProbability]').parent().append('<div style="position: absolute;background: gray;min-height: 22px;width: 156px;margin-top: -24px;opacity: 0.2;"></div>');
    
    FillCloseDate();
    });
    
    function FillCloseDate()
    {
       
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();
        
        if(dd<10) {
            dd='0'+dd
        }
        
        if(mm<10) {
            mm='0'+mm
        }
        
        today = date.(mm+'/'+dd+'/'+yyyy);
        
        $('[Id$=closedate]').val(today);
      
    }
    
    
    function StageChangeEvent(){
        $('[Id$=iptStage]').change(function(){
        
            if($('[Id$=iptStage]').val()=="Closed Won"){
                $('[Id$=iptProbability]').val(100);              
                $('[Id$=iptNumberOfInstallment]').attr('disabled',false);
            }else if($('[Id$=iptStage]').val()=="Proposal/First Quote sent"){
                $('[Id$=iptProbability]').val(40);
                DisableInastllment();
            }else if($('[Id$=iptStage]').val()=="Transferred - B2B"){
                $('[Id$=iptProbability]').val(50);
                DisableInastllment();
            }else if($('[Id$=iptStage]').val()=="Negotiation/Review"){
                $('[Id$=iptProbability]').val(60);
                DisableInastllment();
            }else if($('[Id$=iptStage]').val()=="Closed Lost"){
                $('[Id$=iptProbability]').val(0);
                DisableInastllment();
            }else if($('[Id$=iptStage]').val()==""){
                $('[Id$=iptProbability]').val(0);
            }            
        });
    }
</script>

<apex:pageMessages ></apex:pageMessages>
 <apex:form id="mainFrm">
        <apex:pageBlock id="pbMain">
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!Save}"/>
                <apex:commandButton value="Cancel" action="{!Cancel}"/>
                
            </apex:pageBlockButtons>
            <apex:pageblockSection title="Opportunity Information" id="pbsOppInfo" >
                <apex:outputField value="{!Opportunity.Ownerid}" id="ow" rendered="{!$CurrentPage.parameters.id!=null}" />
                <apex:repeat id="rptBasicInfo" value="{!$ObjectType.Opportunity.FieldSets.OpportunityInfo}" var="inOppInfo">                    
                      <apex:inputField id="infldBasicInfo" value="{!Opportunity[inOppInfo]}"></apex:inputField>
                </apex:repeat>
                
                <apex:inputField value="{!Opportunity.OppContact__c}" id="iptContact" rendered="{!if($CurrentPage.Parameters.id !='' && Opportunity.OppContact__c != '',true,false)}"/>   
                <apex:inputField value="{!Opportunity.StageName}" id="iptStage" required="true"/>   
               <!-- <apex:inputField value="{!Opportunity.Probability}" id="iptProbability"/> -->
            </apex:pageblockSection>
            <div style="display:none">
                <apex:inputField value="{!Opportunity.Probability}" id="iptProbability"/>
                <apex:inputField id="closedate" value="{!Opportunity.closedate}"/>
                
            </div>
            <apex:pageblockSection title="Holiday Details" >                
                <apex:repeat id="rptHolidayInfo" value="{!$ObjectType.Opportunity.FieldSets.Holiday_Details}" var="inHoliday">
                      <apex:inputField id="inHolidayInfo" value="{!Opportunity[inHoliday]}"  required="{!OR(inHoliday.required, inHoliday.dbrequired)}"></apex:inputField>
                </apex:repeat>
            </apex:pageblockSection>
           <!--  <apex:pageBlockSection title="OpportunityInformation" id="pbsOppInfo">
                <apex:outputText value="{!$User.FirstName} {!$User.LastName}" label="Opportunity owner" rendered="{!$CurrentPage.parameters.id==null}" style="margin-left:10px;"/>
                <apex:inputField value="{!Opportunity.Name}" id="iptname" required="true"/>
                <apex:inputField value="{!Opportunity.Accountid}" id="iptSalutation" />
                <apex:inputField value="{!Opportunity.OppContact__c}" id="idcontact" required="true"/>
                <apex:inputField value="{!Opportunity.Type}" id="ipttype" required="true"/>   
                <apex:inputField value="{!Opportunity.Lpti_Group_Size__c}" id="iptgroupsource" required="true"/>
                <apex:inputField value="{!Opportunity.LeadSource}" id="iptLeadSource" />           
                <apex:inputField value="{!Opportunity.Amount}" id="iptAmount" />
                <apex:inputField value="{!Opportunity.CloseDate}" id="iptclosedate" required="true"/>
                <apex:inputField value="{!Opportunity.StageName}" id="ipstage" required="true"/>
                <apex:inputField value="{!Opportunity.Probability}" id="iptProbability"/>
                <apex:inputField value="{!Opportunity.Lpti_Mobile_Number__c}"  id="iptCompany"/>
              </apex:pageBlockSection>
              
              <apex:pageBlockSection title="Holiday Details">
                <apex:inputField value="{!Opportunity.Lpti_Business__c}" id="ipbusiness" required="true" />
                <apex:inputField value="{!Opportunity.Lpti_Product__c}" id="ipproduuct" required="true"/>
                <apex:inputField value="{!Opportunity.Lpti_Tour_Type__c}" id="iptour" required="true"/>
                <apex:inputField value="{!Opportunity.Lpti_Circuit_Program__c}" id="iptcircuit" required="true"/>
                <apex:inputField value="{!Opportunity.Lpti_Level__c}" id="iptlevel" required="true"/>
                <apex:inputField value="{!Opportunity.Lpti_Duration_of_Travel__c}" style="width:150px;" id="iptDestinationLocation" />
                <apex:inputField value="{!Opportunity.TUI_Month_of_travel__c}" id="iptReg" />
                <apex:inputField value="{!Opportunity.Lpti_Children_6_12__c}" id="ipchildren" />
                <apex:inputField value="{!Opportunity.Lpti_Children_0_5__c}" id="iptchildren5" />
              </apex:pageBlockSection>
                
              <apex:pageBlockSection title="Passenger Details">
                <apex:inputField value="{!Opportunity.Lpti_Duration_of_Travel__c}" style="width:150px;" id="iptDestinationLocation" />
                <apex:inputField value="{!Opportunity.TUI_Month_of_travel__c}" id="iptReg" />
                <apex:inputField value="{!Opportunity.Lpti_Children_6_12__c}" id="ipchildren" />
                <apex:inputField value="{!Opportunity.Lpti_Children_0_5__c}" id="iptchildren5" />
              </apex:pageBlockSection>  -->
              
              <apex:pageBlockSection title="Additional Information">
                <apex:inputField value="{!Opportunity.Lpti_Lost_Reasons__c}" id="ipbaddress" style="width:150px;" />
              </apex:pageBlockSection>
           
        </apex:pageBlock>
 </apex:form>
            
</apex:page>

Monday 23 June 2014

Web to lead with record Type

<!--  ----------------------------------------------------------------------  -->
<!--  NOTE: Please add the following <META> element to your page <HEAD>.      -->
<!--  If necessary, please modify the charset parameter to specify the        -->
<!--  character set of your HTML page.                                        -->
<!--  ----------------------------------------------------------------------  -->

<META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8">

<!--  ----------------------------------------------------------------------  -->
<!--  NOTE: Please add the following <FORM> element to your page.             -->
<!--  ----------------------------------------------------------------------  -->

<form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">

<input type=hidden name="oid" value="00D90000000roim">
<input type=hidden name="retURL" value="http://www.kg91.weebly.com">

<!--  ----------------------------------------------------------------------  -->
<!--  NOTE: These fields are optional debugging elements. Please uncomment    -->
<!--  these lines if you wish to test in debug mode.                          -->
<!--  <input type="hidden" name="debug" value=1>                              -->
<!--  <input type="hidden" name="debugEmail" value="kg91.in@gmail.com">       -->
<!--  ----------------------------------------------------------------------  -->

<label for="first_name">First Name</label><input  id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br>

<label for="last_name">Last Name</label><input  id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br>

<label for="email">Email</label><input  id="email" maxlength="80" name="email" size="20" type="text" /><br>

<label for="company">Company</label><input  id="company" maxlength="40" name="company" size="20" type="text" /><br>

<label for="city">City</label><input  id="city" maxlength="40" name="city" size="20" type="text" /><br>

<label for="state">State/Province</label><input  id="state" maxlength="20" name="state" size="20" type="text" /><br>

<label for="Campaign_ID">Campaign</label><select  id="Campaign_ID" name="Campaign_ID"><option value="">--None--</option><option value="70190000000gZI1">GC Product Webinar - Jan 7, 2002</option>
<option value="70190000000gZI2">User Conference - Jun 17-19, 2002</option>
<option value="70190000000gZI3">DM Campaign to Top Customers - Nov 12-23, 2001</option>
<option value="70190000000gZI4">International Electrical Engineers Association Trade Show - Mar 4-5, 2002</option>
</select><br>

<label for="recordTypeID">RecordType</label><select  id="RecordType_ID" name="recordTypeID"><option value="">--None--</option><option value="01290000000tzEVAAY">A</option>
<option value="701290000000tcJ3AAI">for Cars</option>
</select><br>

<input type="submit" name="submit">

</form>

Thursday 19 June 2014

Mock Call Out Class

Open topic with navigation

Testing HTTP Callouts by Implementing the HttpCalloutMock Interface

Provide an implementation for the HttpCalloutMock interface to specify the response sent in the respond method, which the Apex runtime calls to send a response for a callout.

    global class YourHttpCalloutMockImpl implements HttpCalloutMock {      global HTTPResponse respond(HTTPRequest req) {          // Create a fake response.
        // Set response values, and
        // return response. } }
Note
  • The class that implements the HttpCalloutMock interface can be either global or public.
  • You can annotate this class with @isTest since it will be used only in test context. In this way, you can exclude it from your organization’s code size limit of 3 MB.

Now that you have specified the values of the fake response, instruct the Apex runtime to send this fake response by calling Test.setMock in your test method. For the first argument, pass HttpCalloutMock.class, and for the second argument, pass a new instance of your interface implementation of HttpCalloutMock, as follows:

    Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImpl());

After this point, if an HTTP callout is invoked in test context, the callout is not made and you receive the mock response you specified in the respond method implementation.

Note
If the code that performs the callout is in a managed package, you must call Test.setMock from a test method in the same package with the same namespace to mock the callout.

This is a full example that shows how to test an HTTP callout. The interface implementation (MockHttpResponseGenerator) is listed first. It is followed by a class containing the test method and another containing the method that the test calls. The testCallout test method sets the mock callout mode by calling Test.setMock before calling getInfoFromExternalService. It then verifies that the response returned is what the implemented respond method sent. Save each class separately and run the test in CalloutClassTest.

    @isTest                          
global class MockHttpResponseGenerator implements HttpCalloutMock { // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) { // Optionally, only send a mock response for a specific endpoint
        // and method. System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint()); System.assertEquals('GET', req.getMethod()); // Create a fake response HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"foo":"bar"}'); res.setStatusCode(200); return res; } }
    public class CalloutClass {      public static HttpResponse getInfoFromExternalService() {          HttpRequest req = new HttpRequest();          req.setEndpoint('http://api.salesforce.com/foo/bar');          req.setMethod('GET');          Http h = new Http();          HttpResponse res = h.send(req);          return res;      }  }
    @isTest                          
private class CalloutClassTest { @isTest static void testCallout() { // Set mock callout class Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. HttpResponse res = CalloutClass.getInfoFromExternalService(); // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type'); System.assert(contentType == 'application/json'); String actualValue = res.getBody(); String expectedValue = '{"foo":"bar"}'; System.assertEquals(actualValue, expectedValue); System.assertEquals(200, res.getStatusCode()); } }
© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.

 

Tuesday 17 June 2014

Method for Removing Selected Record from list

public void RemoveThis()
      {
         List<Integer> i=new List<Integer>();
         List<WrapClass> lstTemp=new List<WrapClass>();
         for(Integer j=0;j<lstWrap.size();j++)
             {
              if(lstWrap[j].isCheck==true)
                 {
                  i.add(j);
                 }
             }
              m=new List<Integer>();
             for(Integer k=i.size()-1;k>=0;k--)
             {
               m.add(i[k]);
             }
             
         for(Integer objInt:m)
         {
         lstWrap.remove(objInt);
         }
       }

Monday 16 June 2014

sql procedure

/*Procedure*/
ALTER PROC sp_TUI
@pkg_Code VARCHAR(20),
@bid int,
@p_name VARCHAR(20)
AS
BEGIN
SET @pkg_Code=REPLACE(@pkg_Code,'null','')
SET @p_name=REPLACE(@p_name,'null','')
SELECT b_id 'Booking Reference',title 'Lead Pax Title',first_name 'Lead Pax 1st Name',last_name 'Lead Pax 2nd Name',age 'Lead Pax Age',a_code 'Agent Code',
a_name 'Agent name',branch_code 'Branch Code',region_code 'Region Code',Channel,p_Code 'Product Code',b_Type 'Booking Type',p_Type 'Product Type',
pkg_Code 'Package Code',pkg_Name 'Package Name',b_Booking_Date 'Booking Date',b_Dep_Date 'Departure Date',b_No_of_Adults 'No of Adults',
b_No_of_Childs 'No of Childs',b_No_of_Infants 'No of Infants',outbond_dep_airport 'Outbound Departure Airport',outbond_Arrival_airport 'Outbound Arrival Airport',
inbond_dep_airport 'Inbound Departure Airport',inbond_Arrival_airport 'Inbound Arrival Airport',S_Type 'Service Type',s_Code 'Service Code',s_name 'Service Name',S_Dep 'Service Departure',
S_Arr 'Service Arrival',S_Cost 'Service Cost',S_Sale_price 'Service Sale Price',S_Margin 'Service Margin',S_Margin_percent 'Service Marging %',total_booking_cost 'Total Booking Cost',
booking_margin 'Booking Margin',booking_marging_percent 'Booking margin %',p_Name 'Product name',mobile 'Opp Mobile',email 'Opp Email',
booking_confirmed,
pli_days 'Day'
FROM Booking   
JOIN Product  ON Booking.p_id_r=Product.p_id  
JOIN Opportunity ON Booking.opp_id_r=Opportunity.opp_id
JOIN Package  ON Booking.pkg_id=Package.pkg_id  
JOIN TUI_Service ON Booking.b_id=TUI_Service.b_id_r
JOIN Package_Line_Item ON TUI_Service.pkg_line_item_id_r=Package_Line_Item.pkg_line_item_id
JOIN Agent  ON Booking.a_id_r=Agent.a_id

where (pkg_Code=@pkg_Code OR ISNULL(@pkg_Code,'')='')
AND (p_Name=@p_name OR ISNULL(@p_name,'')='')
AND CASE WHEN @bid != 0
    THEN
        b_id
    ELSE
        @bid
    END
    =
    CASE WHEN @bid != 0
    THEN
        @bid
    ELSE
        @bid
    END

--GROUP BY p_Name, pkg_Name, b_id
ORDER BY p_Name, pkg_Name, b_id

END

--exec sp_TUI NULL,14,Null


Friday 13 June 2014

Stop Recursion in Trigger

Stop Recursion:
Trigger:
------------------
trigger trigSplitSalesInvoiceLine on c2g__codaInvoiceLineItem__c (After insert)
{
  if(StopRecursion.runOnce())
   {
     SalesInvoiceLineItemTriggerHandler goToHandler = new SalesInvoiceLineItemTriggerHandler(Trigger.isExecuting,Trigger.size);
     if(Trigger.isAfter && Trigger.isInsert)
      {
        goToHandler.OnAfterInsert(trigger.new);
      }
   }

}
-----------
Class:
public with sharing class SalesInvoiceLineItemTriggerHandler
{
      private boolean isExecuting = True;
      private integer BatchSize = 0;
     
      public SalesInvoiceLineItemTriggerHandler(boolean isExecuting, integer size)
      {
         isExecuting = isExecuting;
           BatchSize = size;
      }
      public void OnAfterInsert(List<c2g__codaInvoiceLineItem__c> triggerNew)
          {
              updateUnitRateWithCordRateInsertNewSILEqualPlacentaRate(triggerNew);
          }
          
       public void updateUnitRateWithCordRateInsertNewSILEqualPlacentaRate(List<c2g__codaInvoiceLineItem__c> lstSalesInvoiceLine)
       {
        if(lstSalesInvoiceLine!=null && lstSalesInvoiceLine.size()>0)
          {
            List<c2g__codaInvoiceLineItem__c > lstInvoiceLine=new List<c2g__codaInvoiceLineItem__c >();
            List<c2g__codaInvoiceLineItem__c > lstInvoiceLine2=new List<c2g__codaInvoiceLineItem__c >();
            for(c2g__codaInvoiceLineItem__c objInvoiceLine:lstSalesInvoiceLine)
               {
               if(objInvoiceLine.Cl_Cord_Rate__c!=null)
                {   
                 c2g__codaInvoiceLineItem__c objIL=new c2g__codaInvoiceLineItem__c(id =objInvoiceLine.id );
                 objIL.c2g__UnitPrice__c=objInvoiceLine.Cl_Cord_Rate__c;
                 objIL.c2g__Product__c=objInvoiceLine.c2g__Product__c;
                 objIL.c2g__Quantity__c=objInvoiceLine.c2g__Quantity__c;
                 lstInvoiceLine.add(objIL);
                }
               }
            for(c2g__codaInvoiceLineItem__c objInvoiceLine:lstSalesInvoiceLine)
               {
               if(objInvoiceLine.Cl_Placenta_Rate__c!=null)
                {
                c2g__codaInvoiceLineItem__c objNewIL=new c2g__codaInvoiceLineItem__c ();
                objNewIL.c2g__UnitPrice__c=objInvoiceLine.Cl_Placenta_Rate__c;
                objNewIL.c2g__Invoice__c=objInvoiceLine.c2g__Invoice__c;
                objNewIL.c2g__OwnerCompany__c=objInvoiceLine.c2g__OwnerCompany__c;
                objNewIL.c2g__Product__c=objInvoiceLine.c2g__Product__c;
                objNewIL.ffbilling__DeriveUnitPriceFromProduct__c=objInvoiceLine.ffbilling__DeriveUnitPriceFromProduct__c;
                lstInvoiceLine2.add(objNewIL);
               }
               }
            if(lstInvoiceLine.size()>0 && lstInvoiceLine2.size()>0)
            {   
            update lstInvoiceLine;
            insert lstInvoiceLine2;
            }
         }
 
       
     }
}

-----------------
Recursion Class:
public Class StopRecursion
{
private static boolean run = true;
public static boolean runOnce()
 {
    if(run)
    {
      run=false;
      return true;
    }
    else
    {
        return run;
    }
 }


}

Wednesday 11 June 2014

sql table creation


CREATE TABLE Opportunity(opp_id INT PRIMARY KEY NOT NULL IDENTITY(0,1),first_name VARCHAR(20),last_name VARCHAR(20),
                          mobile INT,email VARCHAR(30))
CREATE TABLE Product(p_id INT PRIMARY KEY NOT NULL IDENTITY(0,1),p_Name VARCHAR(30),p_Desc VARCHAR(150))
CREATE TABLE Package(pkg_id INT PRIMARY KEY NOT NULL IDENTITY(0,1),pkg_Name VARCHAR(30),pkg_Code VARCHAR(20))
CREATE TABLE Package_Line_Item
(pkg_line_item_id INT PRIMARY KEY NOT NULL IDENTITY(0,1),
 pkg_id_r int REFERENCES Package(pkg_id) NOT NULL,
 pli_days VARCHAR(20),outbond_dep_airport VARCHAR(40),outbond_Arrival_airport VARCHAR(40),inbond_dep_airport VARCHAR(40),
 inbond_Arrival_airport VARCHAR(40)
CREATE TABLE Booking(b_id INT PRIMARY KEY NOT NULL IDENTITY(0,1),opp_id_r INT REFERENCES Opportunity(opp_id) NOT NULL,
p_id_r INT REFERENCES Product(p_id) NOT NULL,pkg_id INT REFERENCES Package(pkg_id) NOT NULL,total_booking_cost int,total_booking_price int,
booking_margin INT,booking_marging_percent INT,booking_confirmed BIT
)

CREATE TABLE Agent(a_id INT PRIMARY KEY NOT NULL IDENTITY(0,1),a_name VARCHAR(30),a_code VARCHAR(20),branch_code VARCHAR(20),region_code VARCHAR(20))

CREATE TABLE TUI_Service(s_id INT PRIMARY KEY NOT NULL IDENTITY(0,1),s_name VARCHAR(20),s_type VARCHAR(20),s_Code VARCHAR(20),
b_id_r INT REFERENCES Booking(b_id) NOT NULL,pkg_id_r INT REFERENCES Package(pkg_id) NOT NULL,
pkg_line_item_id_r INT REFERENCES Package_Line_Item(pkg_line_item_id) NOT NULL
 )
                   
                          
                       

Thursday 5 June 2014

Retrive record from salesforce

package a;

import com.sforce.soap.enterprise.EnterpriseConnection;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.GetUserInfoResult;
import com.sforce.soap.enterprise.UpsertResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class Retrive { public String authEndPoint = "";
EnterpriseConnection con;
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args)
{          String arr[] = new String[] {"0019000000vEcw0"};
            if ( sample.login() )
            {
                        sample.retrieveRecords(arr);
            }
}
public Retrive(String authEndPoint)
{
            this.authEndPoint = authEndPoint;
}
public String getUserInput(String prompt)
{
            String result = "";
            try
            {
                        System.out.print(prompt);
                        result = reader.readLine();
            }
            catch (IOException ioe)
            {
                        ioe.printStackTrace();
            }
            return result;
}
public boolean login()
{
            boolean success = false;
            String userId = getUserInput("UserID: ");
            String passwd = getUserInput("Password + Security Token: ");
            try
            {
                        /* Setting up Username and Password */
                        ConnectorConfig config = new ConnectorConfig();
                        config.setAuthEndpoint(authEndPoint);
                        config.setUsername(userId);
                        config.setPassword(passwd);
                        config.setCompression(true);
                        //config.setProxy("Your Proxy", 80);
                        System.out.println("AuthEndPoint: " + authEndPoint);
                        config.setTraceFile("upsertLogs.txt");
                        config.setTraceMessage(true);
                        config.setPrettyPrintXml(true);

                        System.out.println("\nLogging in ...\n");
                        /* Setting up connection to Salesforce */
                        con = new EnterpriseConnection(config);
                        GetUserInfoResult userInfo = con.getUserInfo();   
                        System.out.println("UserID: " + userInfo.getUserId());
                        System.out.println("\nLogged in Successfully\n");
                        success = true;
            }
            catch (ConnectionException ce)
            {
                        ce.printStackTrace();
            }
            catch (FileNotFoundException fnfe)
            {
                        fnfe.printStackTrace();
            }
            return success;
}
public void updateAcct()
{
            try
            {                      
                        /* Getting Account details */
                        SObject[] upserts = new Account[1];
                        Account upsertAccount = new Account();
                        String acctName = getUserInput("Enter Account name:");
                        String acctNo = getUserInput("Enter Account no:");
                        String phoneNo = getUserInput("Enter phone no:");
                       
                        String extId = getUserInput("Enter External Id:");
                       
                        upsertAccount.setName(acctName);
                        upsertAccount.setPhone(phoneNo);
                        upsertAccount.setAccountNumber(acctNo);
                       
                        upsertAccount.setSLASerialNumber__c(extId);
                       
                        upserts[0] = upsertAccount;
                        System.out.println("\nUpserting...");
                        /* Upserting account records */   
                        UpsertResult[] upsertResults = con.upsert("SLASerialNumber__c",upserts);
                        for (UpsertResult result : upsertResults)
                        {
                                    if (result.isSuccess())
                                    {
                                                System.out.println("\nUpsert succeeded.");
                                                System.out.println(
                                                                        (result.isCreated() ? "Insert" : "Update") +
                                                                        " was performed."
                                                );
                                                System.out.println("Account ID: " + result.getId());
                                    }
                                    else
                                    {
                                                System.out.println("The Upsert failed because: " +
                                                                        result.getErrors()[0].getMessage());
                                    }
                        }
            }
            catch (ConnectionException ce)
            {
                        ce.printStackTrace();
            }
}

public void retrieveRecords(String[] ids) {
  try {
     SObject[] sObjects = con.retrieve("ID, Name, Website",
           "Account", ids);
     // Verify that some objects were returned.
     // Even though we began with valid object IDs,
     // someone else might have deleted them in the meantime.
     if (sObjects != null) {
        for (int i = 0; i < sObjects.length; i++) {
           // Cast the SObject into an Account object
           Account retrievedAccount = (Account) sObjects[i];
           if (retrievedAccount != null) {
              System.out.println("Account ID: " + retrievedAccount.getId());
              System.out.println("Account Name: " + retrievedAccount.getName());
              System.out.println("Account Website: "
                    + retrievedAccount.getWebsite());
           }
        }
     }
  } catch (ConnectionException ce) {
     ce.printStackTrace();
  }
}



}

Tuesday 3 June 2014

ScreenRecorder java

import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Robot;
import java.io.File;
import javax.imageio.ImageIO;
 
class ScreenRecorder {
public static void main(String args[]) {
   try {
       Toolkit tool = Toolkit.getDefaultToolkit();
       Dimension d = tool.getScreenSize();
       Rectangle rect = new Rectangle(d);
       Robot robot = new Robot();
       Thread.sleep(2000);
       File f = new File("screenshot.jpg");
       BufferedImage img = robot.createScreenCapture(rect);
       ImageIO.write(img,"jpeg",f);
       tool.beep();
       } catch(Exception e){
        e.printStackTrace();
      }
    }
}

retrieveRecords using java

Sample Code—Java

This sample retrieves the Id, Name, and Website of the specified Account records. It writes the fields of the retrieved records to the console.

    public void retrieveRecords(String[] ids) {     try {        SObject[] sObjects = connection.retrieve("ID, Name, Website",              "Account", ids);        // Verify that some objects were returned.        // Even though we began with valid object IDs,        // someone else might have deleted them in the meantime.        if (sObjects != null) {           for (int i = 0; i < sObjects.length; i++) {              // Cast the SObject into an Account object              Account retrievedAccount = (Account) sObjects[i];              if (retrievedAccount != null) {                 System.out.println("Account ID: " + retrievedAccount.getId());                 System.out.println("Account Name: " + retrievedAccount.getName());                 System.out.println("Account Website: "                       + retrievedAccount.getWebsite());              }           }        }     } catch (ConnectionException ce) {        ce.printStackTrace();     }  }

Replace the current window with a new window:

Example

Replace the current window with a new window:

var myWindow = window.open("", "_self");
myWindow.document.write("<p>I replaced the current window.</p>");