Saturday 13 August 2011

Dynamic Multi Select Picklist on Vfpage.


Hai friends,
      I came with new post, This Post illustrates how to display Multiselect Picklist on Vfpage and how the values are populating into multiselect picklist.I am giving example like, we can field Type picklist on account pagelayout,now i am taking that field and populating that fields data in to multiselect picklist and selected values in to new field 'Selected values' custom field and while editing that record,loading values in to multiselect picklist.
                            
         
First we need to get the picklist values,for this we need to use describe object methods.
 Schema.DescribeFieldResult fieldResult = Schema.sObjectType.Account.fields.Type.getSObjectField().getDescribe();
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
   for( Schema.PicklistEntry f : ple)
   {       options .add(new SelectOption(f.getLabel(), f.getValue()));       originalvalues.add(f.getLabel());       system.debug('********PICK*******'+originalvalues);    }      
 we can use above code to get all the picklist values from Type field  from Account object.
 Now we need to load this values in to select options and  process the remaining functionality,i am giving total code for that please go through that you can understand the functionality
Controller
 public class multiselect1 {
    String strget='';     
public string Accid{get;set;}     
public String accName { get; set; }     
Set<string> originalvalues = new Set<string>();     
Public List<string> leftselected{get;set;}     
Public List<string> rightselected{get;set;}    
 Set<string> leftvalues = new Set<string>();     
Set<string> rightvalues = new Set<string>();    
 List<SelectOption> options = new List<SelectOption>();     
String selectedvalue='';     List<string> lstFinal = new List<string>();  
public List<SelectOption> getCountries() // getting picklist values and populatinting into multiselec picklist. 
{   
List<SelectOption> options = new List<SelectOption>();    
Schema.DescribeFieldResult fieldResult = Schema.sObjectType.Account.fields.Type.getSObjectField().getDescribe();    
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();       
for( Schema.PicklistEntry f : ple)
{       
options .add(new SelectOption(f.getLabel(), f.getValue()));       
originalvalues.add(f.getLabel());          
}          return options;  
public multiselect1()
{        
 getCountries();         
GetEdit();         
leftselected = new List<string>();        
 rightselected = new List<string>();         
leftvalues.addAll(originalValues);      
}     
public PageReference selectclick()
{        
 rightselected.clear();         
for(String s : leftselected){  // left side selected values             
leftvalues.remove(s);             
rightvalues.add(s); // adding to right side        
 }         return null;     
}     
public PageReference unselectclick(){  
   leftselected.clear();       
 for(String s : rightselected){ // right side selected values             
rightvalues.remove(s);             
leftvalues.add(s); // adding to left side.         
}         
return null;     
}     
public List<SelectOption> getunSelectedValues()
{         
List<SelectOption> options = new List<SelectOption>();         
List<string> tempList = new List<string>();         
tempList.addAll(leftvalues);         
tempList.sort();         
for(string s : tempList)             
ptions.add(new SelectOption(s,s));         
return options;     
   List<SelectOption> options1 = new List<SelectOption>();     
public List<SelectOption> getSelectedValues()
{         
options1.clear();        
List<string> tempList = new List<string>();        
 tempList.addAll(rightvalues);         tempList.sort();         
for(String s : tempList)         
options1.add(new SelectOption(s,s));         
 System.debug('**********selected Values'+options1 );           
for(integer i=0;i<options1.size();i++) {           
 if(i==0)               
selectedvalue = options1[i].getValue();            
else               
selectedvalue += ','+options1[i].getValue();             
}            
return options1;       
}      
public void Save()         
Account acc = new Account();         
acc.Name=accName;         
acc.Selected_Values__c=selectedvalue;         
insert acc;     
}     
ist<Account> selAcc = new list<Account>();     
public list<Account> GetEdit() 
{     
selAcc=[select Name,Selected_Values__c from Account where id=:ApexPages.currentPage().getParameters().get('id') and Selected_Values__c !=null ];           
strget =selAcc[0].Selected_Values__c;         
 list<String> lstSplitData =strget.split(',');          
AccName=selAcc[0].Name;         
 if(lstSplitData.size()!=null && lstSplitData.size()!= 0&& originalvalues.size()!=null && originalvalues.size()!=0 )          
{           
for(string sSelected : lstSplitData){              
  if(originalvalues.contains(sSelected.trim())){                    
lstFinal.add(sSelected);                
}            
}            
or(string sFinal:lstFinal){                
if(originalvalues.contains(sFinal.trim())){                   
originalvalues.remove(sFinal);                
}              
}          
}          
 rightvalues.addALL(lstFinal);         
 return selAcc;     
}   
}
Vfpage1:-
  <apex:page>
    <apex:form >
<apex:pageBlock tabStyle="Contact">
    <apex:outputLabel > Account Name:</apex:outputLabel><apex:inputText value="{!accName}"/>
        <apex:panelGrid columns="10" id="abcd">
        <apex:outputLabel > Type:</apex:outputLabel>
            <apex:selectList id="sel1" value="{!leftselected}" multiselect="true" style="width:150px" size="5">
                <apex:selectOptions value="{!unselectedvalues}" />
            </apex:selectList>
                <apex:panelGroup >
                    <br/>
                    <apex:image value="{!$Resource.multiselect}">
                        <apex:actionSupport event="onclick" action="{!selectclick}" reRender="abcd"/>
                    </apex:image>
                    <br/><br/>
<apex:image value="{!$Resource.multiunselect}">
                        <apex:actionSupport event="onclick" action="{!unselectclick}" reRender="abcd"/>
                    </apex:image>
                </apex:panelGroup>
            <apex:selectList id="sel2" value="{!rightselected}" multiselect="true" style="width:150px" size="5">
                <apex:selectOptions value="{!SelectedValues}" />
            </apex:selectList>
        </apex:panelGrid>
          <apex:commandButton value="Save" action="{!Save}"/>
  </apex:pageBlock>
  </apex:form>
  </apex:page>
 Execute this  by passing id to this page as Query string parameter.
please make sure before trying this,create a field "Selected_Values__c".
and upload select and unselect arrows in the static resources
Cheers,
Haribabu Amudalapalli

Sunday 31 July 2011

Overriding Record Type with Vfpage.

Hai Friends this time cam with important topic "Overriding RecordType with Vfpage".This is Very simple and impotant.We can't achieve this Customization, we need to write Script for this.
Step1:-
First Create a Recordtype on an object.
Goto-->Setup-->Appsetup-->Create-->Object--> Create Record Type.
 Suppose like 'Accountrecordtype',
Step2:-
Create Vfpage ,in that Vfpage Code include following code for overriding record type with Vfpage.
===============================
<script language="javascript">

    if('{!account.RecordType.name}' != 'Accountrecordtype'){
        window.location = '/{!account.id}?nooverride=1';
    }
</script>
================================
Now Override the View button with that page.
Now click on the record which is having  Accountrecordtype Record type.

Cheers,
Haribabu Amudalapalli


Monday 25 July 2011

Adding Rows Dynamically to Page block Table

Now i am going to explain a simple example,i.e how we can add rows dynamically to Pageblocktable,how to save records.
Screen:-
   <apex:page controller="multiAccountInsert">
<apex:form >
<apex:sectionHeader title="flexandsalesforceblog" subtitle="AddRows" help="Http://flexandsalesforce.blogspot.com"/>
   <apex:pageBlock title="Add row Dynamically" >
     <apex:pageBlockButtons location="bottom">
         <apex:commandButton value="Save" action="{!save_close}" rerender="error"/>
       </apex:pageBlockButtons>
       <Div align="right">
             <apex:inputText value="{!num}" style="width:45px"/>
             <apex:commandButton value="Add rows" action="{!add_rows}"/> 
       </Div>
       <br/>
      <apex:pageBlockTable value="{!accts}" var="a" id="table">
         <apex:column headerValue="Name">
               <apex:inputField value="{!a.Name}"/>
          </apex:column>
          <apex:column headerValue="phone">
             <apex:inputField value="{!a.phone}"/>
         </apex:column>
         <apex:column headerValue="website">
             <apex:inputField value="{!a.website}"/>
         </apex:column>
       </apex:pageBlockTable>
   </apex:pageBlock>
    </apex:form>
</apex:page>


AddrowController:-



public class addrowCon

  public integer num { get; set; }
  public List<Account> accts {get; set;} 
  public addrowCon()
  {
     accts = new List<Account>(); 
     accts.add(new Account());    
  }
   public PageReference add_rows() {
    for(integer i=0;i<num ;i++)
        {
          accts.add(new Account());    
        }
        
        return null;
     }
  public PageReference save_close()
  {       insert accts;
     PageReference home = new PageReference('/home/home.jsp');
     home.setRedirect(true);
     return home;
  }
}

Tuesday 19 July 2011

Salesforce To Salesforce

Hai Friends, Now i came with the topic "Salesforce to Salesforce",
Introduction :- Salesforce to Salesforce enables you to share records among the business partners.
Step1:-
To establish connection from one organization to another salesforce organization ,we need to enable settings first in both organizations.
Set up--> AppSetup-->Customize-->Salesforce to Salesforce--> Settings.
After enabling settings we need to add another salesforce organization Name and it's Email as Contact in to parent salesforce organization.
Step2:-
Now you can find Tab 'Connections', add that Tab to Tabs bar.
Step3:-  Sending Invitation to another organization.
Now click on 'Connection Tab',click on New--> Select  the contact ,that we have created as per in earlier step--> Click on Save&Send Invite.
Then Email will send to Email,which is associated in that contact.
Step4:-
In that Email,we can get an Link,Click on link and give the login details of client (add contact  sales force organization login details).Now you can see the connection invitation in child salesforce organization.
Click on Accept,Now this allows you to share lead, opportunity, account, contact, task, product, opportunity product, case, case comment, attachment, or custom object records with your business partners. With Salesforce to Salesforce, you can share records with one or more connections, and each connection can accept records you share with them - even if other connections have accepted the same record.
Step 5:- I want to share Accounts
First publish this object from parent connection,for that
Click connection detail page,there you can find the Related list "Publish Object",there you can find button 'publish/unpublish'.Click on that button ,then in new window you can see all the available objects for connection.select Account click on Save.
Now goto business partner Organization,on Connection Detail page you can find related list for Subscribe object, click on button 'subscribe/unsubscribe',click on that button,select object from pick list and click on save. Now to share account records goto parent Salesforce organization ,select Account records from list view of Account records and click on 'Forward to Connections', there you can find list of  Available connections in your organization,select organization and click on save.
Then that Account record will be created in Account object of the business partner.
In this way we can share account records from parent org to business partner organization.
Step 5:- I want to share  contact and opportunities associated with an Account record
We can achieve this by publishing contacts and opportunity objects to business partner and he must subscribe to that objects also.Now send the account record which is associated with above contact and opportunity objects as we discuss in earlier step.

Questions
1. My organization Having 15000 records in Accounts object, can we transfer all the records in one step?
---> Yes, you can achieve this by writing  Apex class. I am giving code for this please go through once you can under stand easily.
Controller:-

global class SendOldRecord
{
        public void sendrec(list<Account> ls)
        {
            //This list declaration for PartnerNetworkrecords
            List<PartnerNetworkRecordConnection> lstShareRecords = new List<PartnerNetworkRecordConnection>();
            //This list declaration for the Connections with this Organization.
            List<PartnerNetworkConnection> connMap=[select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection
                    where ConnectionStatus = 'Accepted' and ConnectionName='Appshark Software Pvt Ltd'];
            //This for is to loop all the connections
                    for(PartnerNetworkConnection network : connMap) 
                    {    
                        for(Account acc:ls)
                        {
                        //object declaration for PartnerNetwork
                        PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();
                        system.debug('Second for loop');
                        newrecord.ConnectionId = network.Id;
                        newrecord.LocalRecordId = acc.id;  
                        newrecord.RelatedRecords = 'Contact';
                        newrecord.SendClosedTasks = true;
                        newrecord.SendOpenTasks = true;
                        newrecord.SendEmails = true;
                        //All the Records are added to the PartnerNetwork
                        lstShareRecords.add(newrecord);
                        }
                   }
              system.debug('List\n'+lstShareRecords);
             //These Records are inserted into Partnernetwork
             //using lstShareRecords.
              insert lstShareRecords;
        }
}
in the case of bulk records , we need to handle them in Batch process,for i have implemented following batch class and pass to list of accounts at every run,
Batch Controller:-
global class RecordBatchApex implements Database.Batchable<Account>
{
global list<Account> start(Database.BatchableContext bc)
{       
    list<account> lstAcc = [select Id from Account];
    return lstAcc;
}

global void execute(Database.BatchableContext bc,List<Account> lstAccount)
{        
system.debug('*******************Execute of Batch Apex***********');
system.debug(lstAccount);
sendoldrecord od=new sendoldrecord();
od.sendrec(lstAccount);
}
//BatchApex Completes
// execution with this finish method
global void finish(Database.BatchableContext BC)
{
system.debug('****Finished*****');
}
Once run that code even from System log,then you can find all the records in business partner login.

2. I want to  insert newly created Account in to partner's organization.
In this Scenario we will go for Apex trigger to create newly inserted account into partner's Organization.

Trigger autoforwardAccount on Account(after insert)
{
String UserName = UserInfo.getName();
String orgName = UserInfo.getOrganizationName();
List<PartnerNetworkConnection> connMap = new List<PartnerNetworkConnection>(
[select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection where ConnectionStatus = 'Accepted']
);
System.debug('Size of connection map: '+connMap.size());
List<PartnerNetworkRecordConnection> prncList = new List<PartnerNetworkRecordConnection>();
for(Integer i =0; i< Trigger.size; i++)
{
Account acc = Trigger.new[i];
String acId = acc.Id;
System.debug('Value of AccountId: '+acId);
for(PartnerNetworkConnection network : connMap)
{
String cid = network.Id;
String status = network.ConnectionStatus;
String connName = network.ConnectionName;
String AccountName = acc.Name;
System.debug('Connectin Details.......Cid:::'+cid+'Status:::'+Status+'ConnName:::'+connName+'AccountName:::'+AccountName);
if(AccountName !=Null)
{
PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();
newrecord.ConnectionId = cid;
newrecord.LocalRecordId = acId;
newrecord.SendClosedTasks = true;
newrecord.SendOpenTasks = true;
newrecord.SendEmails = true;
System.debug('Inserting New Record'+newrecord);
insert newrecord;
}
}
}
}

3. Can we insert Contact or Opportunity related for an account,while inserting contact or opportunity ?


Yes, We can, for that we need to trigger on Contact/Opportunity ,here we are inserting contact/opportunity related to an account for that we need to specify account Id also. 
            We PartnerNetworkRecordConnection object for sharing records between salesforce to salesforce.
It contains filed 'ParentRecordId',to that filed we need to assign that account id.I have written trigger on conatct , i am giving code for that,you can implement same thing for opportunity also.
               
 Trigger autoforwardContact on Contact(after Insert)
{  
String  UserName = UserInfo.getName(); 
 String orgName = UserInfo.getOrganizationName();  
List<PartnerNetworkConnection> connMap = new List<PartnerNetworkConnection>(   [select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection where ConnectionStatus = 'Accepted']  ); 
System.debug('Size of connection map: '+connMap.size());
 List<PartnerNetworkRecordConnection> prncList = new List<PartnerNetworkRecordConnection>(); 
for(Integer i =0; i< Trigger.size; i++) 

Contact con = Trigger.new[i]; 
String conId = con.Id; 
System.debug('Value of ContactId: '+conId);
for(PartnerNetworkConnection network : connMap)

String cid = network.Id;
String status = network.ConnectionStatus; 
String connName = network.ConnectionName;
String ContactName = con.LastName; 
String Accountid = con.Accountid; 
System.debug('Connectin Details.......Cid:::'+cid+'Status:::'+Status+'ConnName:::'+connName+'ContactName:::'+COntactName);
System.debug('Account ID************'+Accountid);
if(ContactName!= NULL)
{  
System.debug('INSIDE IF');  
 PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();  
 newrecord.ConnectionId = cid;  
 newrecord.LocalRecordId = ConId;  
 newrecord.ParentRecordId= Accountid; // here we are specifying Account ID  
 newrecord.SendClosedTasks = true;   
newrecord.SendOpenTasks = true; 
  newrecord.SendEmails = true;   
System.debug('Inserting New Record'+newrecord);
 insert newrecord; 
}


}        
Using Above Trigger we can Send newly inserted record in to Partner's organization.
I think This may help to any one of us.

Monday 11 July 2011

Insert,Edit,Delete,Clone Records for an object from Vfpage

Hi Friends,
  
I hope below post is very helpful for the learners and help them to understand the basic CRUD operations from VF page.

In the below example, I explained Insert / Edit/Delete /Clone operations on Account object.



Here are the code snippets for VF Page and Controllers.

Vfpage:-
Name :- DML Vfpage
<apex:page Controller="editdeleteCOn" >
<apex:form >
 <apex:sectionHeader title="Edit/Delete" subtitle="Auditing Accounts"/>
 <div align='right'>
 <apex:commandButton value="Insert New" action="{!insertNew}" style="width:150px"/>
  </div>
  <br/>
  <apex:pageBlock >
   <apex:pageBlockTable value="{!lstacc}" var="acc">
     <apex:column >
     {!acc.name}
     <apex:param name="aid" value="{!acc.id}" />
     </apex:column>
     <apex:column value="{!acc.Website}" />
     <apex:column value="{!acc.phone}" />
     <apex:column headerValue="Action" >
      <apex:commandLink value="Edit" action="{!editCon}">
      <apex:param name="cid" value="{!acc.id}" assignTo="{!ecid}"/>
      </apex:commandlink>
      &nbsp;&nbsp;/&nbsp;&nbsp;
      <apex:commandLink value="Delete" action="{!deleteCon}">
      <apex:param name="cid" value="{!acc.id}" assignTo="{!dcid}"/>
      </apex:commandLink>
      &nbsp;&nbsp;/&nbsp;&nbsp;
      <apex:commandLink value="Clone" action="{!cloneCon}">
      <apex:param name="cid" value="{!acc.id}" assignTo="{!ccid}"/>
      </apex:commandLink>
     </apex:column>
   </apex:pageBlockTable>
   <apex:detail subject="{!$CurrentPage.parameters.aid}"/>
  </apex:pageBlock>
  </apex:form>
</apex:page>
Controller:-
public class editdeleteCOn {
 //global declarations
   public String ecid{get;set;} // commandlink edit property
   public String dcid{get;set;} // commandlink delete property
   public String ccid{get;set;} // commandlink clone property
   list<Account> lstacc = new list<Account>();
   list<Account> lstacc1 = new list<Account>();
   // Displaying accounts on vfpage
    public list<Account> getlstacc () {
      lstacc =[select Name,phone,website from Account];
      return lstacc;
    }
    // To redirect to editpage.
     public PageReference editCon() {
       pagereference ref = new pagereference('/apex/dataedit?id='+ecid);
       ref.setRedirect(False);
       return ref;  
    }
    // to delete the selected record
       public pagereference deleteCon() {
        lstacc1 =[Select id,Name from Account where id=:dcid];
        delete lstacc1;
        pagereference ref = new pagereference('/apex/editdelete');
        ref.setredirect(True);
        return ref;  
    }
     // to redirect to insert page.
    public PageReference insertNew() {
    pagereference ref = new pagereference('/apex/accountinsert');
    ref.setRedirect(True);
    return ref;
    }
    // for cloning the records.
    public PageReference cloneCon() {
    account c =  [Select id,Name From account where id =:ccid];
    account cloneaccount = c.clone(false);
    insert cloneaccount;
    pagereference ref = new pagereference('/apex/editdelete');
    ref.setRedirect(True);
    return ref;
    }
}

When you click on Edit link i am redirecting to another vfpage.
Vfpage : dataedit
<apex:page standardController="Account" extensions="savecon">
<apex:form >
  <apex:sectionHeader title="Editing Demo" subtitle="Edit"/>
   <apex:pageBlock tabStyle="Account" >
   <apex:pageBlockButtons location="Bottom">
   <apex:commandButton action="{!save}" value="Save"/>
   </apex:pageBlockButtons>
        <apex:pageBlockSection >
          <apex:inputField value="{!account.Name}"/>
          <apex:inputField value="{!account.Website}"/>
          <apex:inputField value="{!account.phone}"/>
        </apex:pageBlockSection>
   </apex:pageBlock>
</apex:form>
</apex:page>
Controller:savecon
public with sharing class savecon {
    ApexPages.StandardController con;
    public savecon(ApexPages.StandardController controller)
       con=controller;
    }
    public pagereference save()
    {
        con.save();
        return new pagereference(page.editdelete.getUrl());
    }
}
When you click on insert ,i am displaying another page to insert records from there,
Vfpage: accountinsert
<apex:page standardController="Account"  extensions="accountinsertcon">
<apex:form >
  <apex:sectionHeader title="Inserting New" subtitle="Account"/>
   <apex:pageBlock >
      <apex:pageBlockButtons >
      <apex:commandButton value="Save" action="{!save}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection >
     <apex:inputField value="{!account.Name}"/>
     <apex:inputField value="{!account.Phone}"/>
     <apex:inputField value="{!account.Website}"/>
     <apex:inputField value="{!account.AnnualRevenue}"/>
     </apex:pageBlockSection>
   </apex:pageBlock>
</apex:form>
</apex:page>
Controller :accountinsertCon
public class accountInsertCOn {
    ApexPages.StandardController con;
    public accountInsertCOn(ApexPages.StandardController controller) {
    con=controller;
    }
    public pagereference save()
    {
       con.save();
       pagereference ref = new pagereference('/apex/editdelete');
       ref.setRedirect(TRUE);
       return ref;
    }
}
Thank You! I hope This will be useful for one our friends.

Friday 8 July 2011

Generating Random Passwords to Different users.

Hai friends,

I explored on 'How to Generate Passwords Randomly for different users'.

In Apex , we have Crypto class to support encrypt and decrypt mechanism.

Here is the simple logic to generate AES key using crypto class . This key usually uses to encrypt and decrypt the data .

                           Blob blobKey = crypto.generateAesKey(128);
                           String key = EncodingUtil.convertToHex(blobKey);
                           System.debug(key);

Below is the code to generate AES key and sending email to entered email address . 
Controller:-

  public class PasswordGenerator 
{
        public String comments { get; set; }
        public String EmployeeNumber { get; set; }
        public String company { get; set; }
        public String Qualification { get; set; }
        public String Email { get; set; }
        public String Name { get; set; }
         string strPassword ='';
       public List<SelectOption> getQual() {
        List<SelectOption> options = new List<SelectOption>();
       options.add(new SelectOption('--NONE--','------NONE-----'));
        options.add(new SelectOption('MBA','MBA'));
        options.add(new SelectOption('MCA','MCA'));
        options.add(new SelectOption('DEGREE','DEGREE'));
        options.add(new SelectOption('INTER','INTER'));
        options.add(new SelectOption('SCHOOLING','SCHOOLING'));
        return options;
        }
    public static String getPassword(Integer len)
     {
        Blob blobKey = crypto.generateAesKey(128);
        String key = EncodingUtil.convertToHex(blobKey);
        System.debug(key);
        return key.substring(0,len);
     }
    
     public pagereference save()
      {
        String password =PasswordGenerator.getPassword(12);
        Blog_Members__c obj=new Blog_Members__c();
        obj.Name=Name;
        obj.company__c=company ;
        obj.Email__c=Email;
        obj.Employee_Number__c=EmployeeNumber ;
        obj.Comments__c=comments;
        obj.Qualification__c=Qualification ;    
        obj.Password__c = password;
        insert obj;
        sendpassword(Email,password);
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Login Details has been mail to your Registered mail Address .')); 
         company ='';
         Qualification ='';
         EmployeeNumber ='';
         comments ='';
         Email ='';
         Name ='';
         return null; 
      }
      
      public void sendpassword(String Email,String Password)
      {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{Email}; 
        String[] ccAddresses = new String[] {'haribabu.amudalapalli@gmail.com'};
        String Password1 =Password;
        System.debug('hari Testing'+Password1+'Email address'+toAddresses );
        mail.setToAddresses(toAddresses);
        mail.setCcAddresses(ccAddresses);
        mail.setReplyTo('support@acme.com');
        mail.setSenderDisplayName('Salesforce Blog ');
        mail.setSubject('Pass Word From Salesforce Blog');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setPlainTextBody('Your UserName: ' + Email +';/n Pass Word '+Password1 );
        mail.setHtmlBody('Your UserName: ' + Email +'\n Pass Word '+Password1);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     
      } 
  }

Page:-

<apex:page showHeader="false" sidebar="false" Controller="PasswordGenerator" >
<apex:pagemessages />
<apex:form >
<apex:pageBlock tabStyle="Contact" >
<apex:pageBlockButtons location="Bottom">
<apex:commandButton value="Submit" action="{!save}" onclick="success();"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Salesforce Blog Registartion Form" >
Name:<apex:inputtext value="{!Name}"/>
<br/>
Email:<apex:inputtext value="{!Email}" id="email"/>
<br/>
Company:<apex:inputtext value="{!company}"/>
<br/>
EmployeeNumber:<apex:inputtext value="{!EmployeeNumber}"/>
<br/>
Comments about Blog:<apex:inputtextarea value="{!comments}" cols="27" rows="6"/>
<br/>
</apex:pageBlockSection>
</apex:pageBlock> 
</apex:form>              
</apex:page>

Check this once.It's working fine.