Monday, 28 October 2013

Show and Hide example using Apex in Salesforce

Visualforce page:

<apex:page controller="HideAndShow" sidebar="false" showHeader="false" >
<apex:form >
 <p style="font-weight:800; color:#4C0000;">&nbsp;&nbsp;&nbsp;Click the buttons below to experiment
     Hide and Show.</p>
<apex:pageBlock title="Block A" rendered="{!abool}">
        This is Block A.<br/><br/>      
</apex:pageBlock>
<apex:pageBlock title="Block B" rendered="{!bbool}">
        This is Block B.<br/><br/>
</apex:pageBlock>  
<apex:pageBlock >
<apex:commandButton value="Show A" action="{!showA}" rendered="{!sabool}" />
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandButton value="Show B" action="{!showB}" rendered="{!sbbool}" />      
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandButton value="Hide A" action="{!hideA}" rendered="{!habool}" />
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandButton value="Hide B" action="{!hideB}" rendered="{!hbbool}" />
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandButton value="Show A and B" action="{!showAB}" rendered="{!sabbool}"/>
     &nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandButton value="Hide A and B" action="{!hideAB}" rendered="{!habbool}"/>
</apex:pageBlock>
</apex:form>  

</apex:page>

Apex Controller:

public with sharing class HideAndShow {
    public Boolean abool {get;set;}
    public Boolean bbool {get;set;}
    public Boolean sabool {get;set;}
    public Boolean sbbool {get;set;}
    public Boolean habool {get;set;}
    public Boolean hbbool {get;set;}
    public Boolean sabbool {get;set;}
    public Boolean habbool {get;set;}
 
    public HideAndShow()
    {
        sabool = true;
        sbbool = true;
        sabbool = true;
        abool = false;
        bbool = false;
    }
 
    public void showA()
    {
        abool = true;
        check();
    }
 
    public void showB()
    {
        bbool = true;
        check();
    }
   
    public void hideA()
    {
        abool = false;
        check();
    }
 
    public void hideB()
    {
        bbool = false;
        check();
    }
 
    public void showAB()
    {
        abool = true;
        bbool = true;
        check();
    }
 
    public void hideAB()
    {
        abool = false;
        bbool = false;
        check();
    }  
 
    public void check()
    {
        if(abool == true && bbool == false)
        {
            sabool = false;
            sbbool = true;
            habool = true;
            hbbool = false;
            sabbool = true;
            habbool = false;
        }
        else if(abool == false && bbool == true)
        {
            sabool = true;
            sbbool = false;
            habool = false;
            hbbool = true;
            sabbool = true;
            habbool = false;
        }
        else if(abool == true && bbool == true)
        {
            sabool = false;
            sbbool = false;
            habool = true;
            hbbool = true;
            habbool = true;
            sabbool = false;

        }
        else
        {
            sabool = true;
            sbbool = true;
            habool = false;
            hbbool = false;
            sabbool = true;
            habbool = false;
        }
    }  
}



Sunday, 27 October 2013

Radio Button in Salesforce

To create Radio button using apex, use <apex:selectRadio>

Example:

Visual force page:

<apex:selectRadio value="{!searchCategory}" >
    <apex:selectOption itemValue="Member" itemlabel="Member"/>
    <apex:selectOption itemValue="Blog" itemlabel="Blog"/>
    <apex:selectOption itemValue="Photo" itemlabel="Photo"/>
</apex:selectRadio>


Apex:

  public String searchCategory;

  public String getsearchCategory()
 {
  return searchCategory;
 }

 public void setsearchCategory(String searchCategory)
 {
  this.searchCategory = searchCategory;
 }

How to convert sObject to String in Apex

public sObject searchCategory;
String objType = String.valueOf(searchCategory);

Wednesday, 23 October 2013

Reset Password code in VF and Apex

Visual Force Code:

<apex:page controller="Reset">
  <center>
   <apex:form >
   <apex:messages />
    <apex:pageBlock title="Reset Password">
     <b>Reset Your Password</b><br/>&nbsp;
      <apex:panelGrid columns="2">
       Enter Email <apex:inputText value="{!email}"/>
       Enter Password <apex:inputsecret value="{!pass}"/>
       Conform Password <apex:inputsecret value="{!conf_pass}"/>
      </apex:panelGrid>
     <apex:commandButton value="Check In" action="{!Save}"/>
    </apex:pageBlock>
   </apex:form>
  </center>
</apex:page>

Apex Code:

public with sharing class Reset {
    public String conf_pass { get; set; }
    public String pass { get; set; }
    public String email { get; set; }
    list<Registration__c> reg_obj;
    //string email;
    string name;
    string password;
    
    public reset(){
        reg_obj = [select id,Email__c,First_Name__c,Password__c from Registration__c];
    }
    
    public PageReference Save() {
    
        if(pass == conf_pass){
            for(Registration__c reg : reg_obj){
                if(reg.Email__c == email){
                    reg.Password__c = pass;
                    update reg;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Your Password is update now.'));                
                }
            }
        }else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Sorry your password and confirm password are not match'));                
        }
          return null;
    }

}

Login Page Using Salesforce Code

Program for Login Page Using Salesforce with VisualForce and APEX Code :

Visual force  Code:

<apex:page controller="LoginPage" showHeader="false" sidebar="false"  standardStylesheets="true">
<body background="{!$Resource.pic}" width="150" height="150"/>
<apex:form >
<center>
<b>Login Page</b>
<apex:panelGrid columns="2" style="margin-top:2em;">
<b>UserName</b>
<apex:inputText required="true" id="username" value="{!username}"/>
<b>Password</b>
<apex:inputSecret id="password" value="{!password}"/>
<b><apex:messages /></b>
</apex:panelGrid>
<apex:commandButton action="{!loginUser}" value="Login" id="save"/>
<apex:commandButton action="{!Cancel}" value="Cancel" id="cancel"/><br/><br/>
<apex:commandLink action="{!registerUser}" value="Register" id="register"
      immediate="true"/><br/> &nbsp; <br/>
<apex:commandLink action="{!ForgotPassword}" value="Forgot Password"
      id="ForgotPassword"  immediate="true"/>
</center>
</apex:form>
</apex:page>


Apex Code :

public class LoginPage {
    public PageReference ForgotPassword() {
        return page.ForgotPassword;
 }
 public PageReference Cancel() {
    PageReference newPage2 = new PageReference('/apex/login');
        newPage2.setRedirect(true);
        return newPage2;
 }
 public PageReference loginUser() { 
     try{
     List<Registration__c> log=[select Email__c,password__C from Registration__c];
       for(Registration__c obj:log){
       if(obj.Email__c==username && obj.password__c==password){
       //PageReference newPage1 = new PageReference('/apex/new');
       // newPage1.setRedirect(true);
        return page.new;
       }
       }
     }
     catch(Exception E){  
     return null;
     }
 apexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'.Invalid
         Username or Password'));
     return null;
}      
public String password { get; set; }
public String username { get; set; }
public PageReference registerUser() {
PageReference newPage = new PageReference('/apex/reg');
newPage.setRedirect(true);
return newPage;
}
}

Tuesday, 22 October 2013

Forgot Password Code

Code for Forgot Password That sending link of reset password  your Email-id :

<apex:page controller="ForgotPasswordClass" sidebar="false" showHeader="true">
 <apex:form >
 <apex:messages />
  <center>
    <h1>Reset Password</h1>
    <b><p>Did you forget your password? Please enter your username below.</p></b>
     <apex:outputLabel value=" Enter Email ID"/>&nbsp;
     <apex:inputText value="{!user}"/><br/>&nbsp;<br/>
     <apex:commandButton value="submit" action="{!save}"/>
  </center>
 </apex:form>
</apex:page>


Apex program :

public with sharing class ForgotPasswordClass {
 public Registration__c ln{get;set;}
 public String user{get;set;}
     public ForgotPasswordClass(){
      ln=new Registration__c();
     }
    public PageReference Save() {
       //ln.name=user;
        String address = user;
        String[] toAddresses = user.split(':', 0);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setSubject( 'link' );
        email.setToAddresses( toAddresses );
        email.setPlainTextBody( 'http://ststech-developer-edition.ap1.force.com/ResetPassword' );
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        User=null;
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Plz check youe mail id for password...'));
         return null;
    }

}

Saturday, 19 October 2013

Sample JAVA program for Web Service API

package wsc;

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

//import com.sforce.soap.enterprise.DeleteResult;
 
import com.sforce.soap.enterprise.DescribeGlobalResult;
import com.sforce.soap.enterprise.DescribeGlobalSObjectResult;
import com.sforce.soap.enterprise.DescribeSObjectResult;
import com.sforce.soap.enterprise.EnterpriseConnection;
//import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.Field;
//import com.sforce.soap.enterprise.FieldType;
import com.sforce.soap.enterprise.GetUserInfoResult;
//import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.PicklistEntry;
import com.sforce.soap.enterprise.QueryResult;
//import com.sforce.soap.enterprise.SaveResult;
//import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.ConnectionException;

public class QuickstartApiSample 

{
private static BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
EnterpriseConnection con;
String authEndPoint = "";
String passwd = "";
public static void main(String[] args) 
{    
QuickstartApiSample sample = new QuickstartApiSample("https://login.salesforce.com/services/Soap/c/24.0/0DF90000000PX8r");
if ( sample.login() ) 
{
sample.describeGlobalSample();
sample.describeSample();
sample.querySample();
}
}
public QuickstartApiSample(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: ");
try 
{
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("traceLogs.txt");
config.setTraceMessage(true);
config.setPrettyPrintXml(true);

con = new EnterpriseConnection(config);
 
GetUserInfoResult userInfo = con.getUserInfo();
System.out.println("\nLogging in ...\n");
System.out.println("UserID: " + userInfo.getUserId());
System.out.println("User Full Name: " +
userInfo.getUserFullName());
System.out.println("User Email: " +
userInfo.getUserEmail());
System.out.println();
System.out.println("SessionID: " +
config.getSessionId());
System.out.println("Auth End Point: " +
config.getAuthEndpoint());
System.out.println("Service End Point: " +
config.getServiceEndpoint());
System.out.println();
success = true;

catch (ConnectionException ce)
{
ce.printStackTrace();

catch (FileNotFoundException fnfe) 
{
fnfe.printStackTrace();
}
return success;
}
public void logout() 
{
try 
{
con.logout();
System.out.println("Logged out");

catch (ConnectionException ce)
{
ce.printStackTrace();
}
}
/**
* To determine the objects that are available to the logged-in
* user, the sample client application executes a describeGlobal
* call, which returns all of the objects that are visible to
* the logged-in user. This call should not be made more than
* once per session, as the data returned from the call likely
* does not change frequently. The DescribeGlobalResult is
* simply echoed to the console.
*/
public void describeGlobalSample() 
{
try 
{
DescribeGlobalResult describeGlobalResult =
con.describeGlobal();
DescribeGlobalSObjectResult[] sobjectResults =
describeGlobalResult.getSobjects();
for (int i = 0; i < sobjectResults.length; i++) 
{
System.out.println(sobjectResults[i].getName());
}

catch (ConnectionException ce) 
{
ce.printStackTrace();
}
}
/**
* The following code segment illustrates the type of metadata
* information that can be obtained for each object available
* to the user. The sample client application executes a
* describeSObject call on a given object and then echoes
* the returned metadata information to the console. Object
* metadata information includes permissions, field types
* and length and available values for picklist fields
* and types for referenceTo fields.
*/
private void describeSample() 
{
String objectToDescribe = getUserInput("\nType the name of the object to " +
"describe (Example: Account): ");
try 
{
DescribeSObjectResult describeSObjectResult =
con.describeSObject(objectToDescribe);
if (describeSObjectResult != null) 
{
Field[] fields = describeSObjectResult.getFields();
System.out.println("Metadata for the " +
describeSObjectResult.getName() + " SObject"
);
System.out.println("\tActivateable: " +
describeSObjectResult.isActivateable()
);
System.out.println("\tNumber of fields: " +
fields.length
);
if (fields != null) 
{
for (Field field : fields) 
{
//String name = field.getName();
System.out.println("\tField name: " +
field.getName()
);
PicklistEntry[] picklistValues =
field.getPicklistValues();
if (picklistValues != null && picklistValues.length > 0) 
{
System.out.println("\t\tPicklist values: ");
for (int j = 0; j < picklistValues.length; j++) 
{
if (picklistValues[j].getLabel() != null) 
{
System.out.println("\t\tValue: " +
picklistValues[j].getLabel()
);
}
}
}
String[] referenceTos = field.getReferenceTo();
if (referenceTos != null && referenceTos.length > 0) 
{
System.out.println("\t\tThis field references the " +
"following objects:"
);
for (int j = 0; j < referenceTos.length; j++) 
{
System.out.println("\t\t" + referenceTos[j]);
}
}
}
}
}

catch (ConnectionException ce) 
{
ce.printStackTrace();
}
}
public void querySample() 
{
try 
{
String soqlQuery = "SELECT FirstName, LastName FROM Contact";
QueryResult result = con.query(soqlQuery);
boolean done = false;
if (result.getSize() > 0) 
{
System.out.println("\nLogged-in user can see " +
result.getRecords().length +
" contact records."
);
while (! done) 
{
SObject[] records = result.getRecords();
for ( int i = 0; i < records.length; ++i ) 
{
Contact con = (Contact) records[i];
String fName = con.getFirstName();
String lName = con.getLastName();
if (fName == null) 
{
System.out.println("Contact " + (i + 1) +
": " + lName
);

else 
{
System.out.println("Contact " + (i + 1) + ": " +
fName + " " + lName
);
}
}
if (result.isDone()) 
{
done = true;

else 
{
result =
con.queryMore(result.getQueryLocator());
}
}

else 
{
System.out.println("No records found.");
}
System.out.println("\nQuery succesfully executed.");

catch (ConnectionException ce) 
{
ce.printStackTrace();
}
}
}