Thursday, June 21, 2018

Closing window in Visualforce

Using JavaScript:

<apex:page showChat="false" wizard="true" sidebar="false" >
<!-- Javascript -->
<script type = "text/javascript">
    function winClose()
    {
        self.close();
    }
</script>
<!-- End of Javascript-->

<apex:commandButton onComplete = "winClose();">

</apex:page>

Using Apex PageReference :

public PageReference method(){
        if(variable== null || variable == ''){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter variable'));
            return null;

        }else{
return new PageReference('javascript:window.close()');
}

Wednesday, June 13, 2018

Difference between deactivate and freeze user in salesforce

In some cases, you can’t immediately deactivate a user such as when a user is selected in a custom hierarchy field or a user that’s assigned as the sole recipient of a workflow email alert. To prevent users from logging into your organization while you perform the steps to deactivate them you can freeze users.
  • Freezing user doesn’t make their user licenses available for use in your organization.
  • Deactivating a user will be available user licenses available for use in your organization.

Friday, May 18, 2018

Salesforce Interview Questions and Answers




1. What is Cloud Computing ?
Ans:
Cloud Computing is an approach to provide the following services -
  • SAAS (Software As A Service)
  • PAAS (Platform As A Service)
  • IAAS (Infrastructure As A Service)
With this approach everything can be done in internet (Using Application, Developing Application and distributing the hardware), no need of any minimum hardware requirements and no need to install any software in local system.

2. What is Salesforce?
Ans:
  1. Salesforce is a company which provides a web based tool called Salesforce
  2. Salesforce by following the Cloud Computing approach, providing SAAS and PAAS
  3. SAAS: Providing Sales, Marketing and Call Center applications as a service
  4. PAAS: Providing Force.com platform in which we can develop Apex (Programming language similar to Core Java) and Visualforce (Mark up language similar to HTML) logic.
7. What is the architecture of the salesforce?
Ans:
MVC (Model View Controller ) Architecture Contains three components Model,View and Controller.

Model is the Database ,
View is the user interface ,
Controller is the Business Logic.

Model View Controller architecture separates the user interface layer which is called VIEW from the data layer called MODEL
Controller layer is between Model layer and View layer. This layer connects both View and Model.

Salesforce follows MVC architecture,

In Salesforce point of view 

Model component will have Standard objects and Custom objects,which will store Data.

View component defines how the data is represented. Visualforce pages, Standard pages are the view components. Page layouts,Apps and Tabs are also comes under this components.

Controller components defines the business logic. Here we have standard controller and custom controllers. Some of the components under this category are Apex classes, triggers, workflows, approvals and validation rules,(Save, Edit, New, Cancel and Delete - upon click on these button salesforce execute some logic from controller).

8. What is the difference between 15 digit and 18 digit id in Salesforce?
Ans:
  • In Salesforce, whenever user create any component (Object, field, tab etc...) or record then salesforce will generate an unique id with which user can identify the record or component.
  • After creating the record, in the URL user can see the id of the record which is of 15 digits length.
  • Through user interface user always see 15 digit id which is Cases-Sensitive.
  • If the user query the existing records from the database through API (Either from Query Tool or from a program), it will always return 18 digit id which is Case-Insensitive.
  • Last 3 digits of the 18 digit represents checksum of the capitalization of 15 digit id.
  • Based on the first 3 digits user can identify the object of the record.
  • All the records belongs to same object will contain same first 3 digits.
9.Object Relationships?
Ans:
  1. Master-detail
  2. Many-to-many
  3. Lookup
  4. External lookup : An external lookup relationship links a child standard, custom, or external object to a parent external object
  5. Indirect lookup : An indirect lookup relationship links a child external object to a parent standard or custom object.
  6. Hierarchical : A special lookup relationship available for only the user object. It lets users use a lookup field to associate one user with another that does not directly or indirectly refer to itself.
10. Difference between standard controller and custom controller ?
Ans:
Standard controller:

If VF uses Standard controllers then it contains the functionality and logic that are used for standard Salesforce pages. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a standard Account edit page.
A standard controller exists for every Salesforce object that can be queried using the Force.com API.
Custom controller:

custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.
  1. Override existing functionality
  2. Make new actions available to the page
  3. Customize the navigation
  4. Use HTTP callouts or web services
  5. Have greater control of how information is accessed on the page
controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when:
  • You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete.
  • You want to add new actions.
11. What is the difference between workflow and process builder ?
Ans:
You can use the Process Builder to perform more actions than with workflow:
  • Create a record
  • Update any related record
  • Use a quick action to create a record, update a record, or log a call
  • Launch a flow
  • Send an email
  • Post to Chatter
  • Submit for approval
  • Call apex methods
But the process builder doesn’t support outbound messages.
Workflow does only 4 actions
  • Create Task
  • Update Field
  • Email Alert
  • Outbound Message
12. What is the outbound message ?
Ans:
Outbound messaging is part of the workflow rule functionality in Salesforce. Workflow rules watch for specific kinds of field changes and trigger automatic Salesforce actions, such as sending email alerts, creating task records, or sending an outbound message to external services. Outbound messages can contain database field values.

Outbound messaging uses the notifications() call to send SOAP messages over HTTP(S) to a designated endpoint when triggered by a workflow rule.

After you set up outbound messaging, when a triggering event occurs, a message is sent to the specified endpoint URL. The message contains the fields specified when you created the outbound message. Once the endpoint URL receives the message, it can take the information from the message and process it. 

13. Difference between SOAP and REST API ?
Ans:
SOAP : Simple Object Access Protocol
REST : Representational State Transfer
* REST and SOAP are the two web service frameworks available on the Force.com platform.
* The SOAP API uses authentication with username and password, and communicates using XML messages. There are different API's to work with the Enterprise, Partner, Bulk, Metadata etc.
*The REST API uses HTTP to authenticate, it uses a token authentication and can use OATH to authenticate, it communicates using JSON messages.
*REST API is generally lighter weight than the SOAP API, works well with mobile applications especially.
JSON is mostly preferred as it is light weight and therefore REST API's are most suited for mobile and web applications.
* SOAP works with WSDL and REST works with GET, POST, PUT, DELETE
* SOAP Handles large data load and fit for large enterprise applications and REST Handles less data and fit for mobile and web applications.

14.How can you expose REST API ?
Ans:




Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service.
At Class level

@RestResource(urlMapping='/yourUrl')
 
At Method Level

@HttpDelete
@HttpGet
@HttpPatch
@HttpPost    - Create Only
@HttpPut     - Create or Update

15. Order of Execution?
Ans:
1. Old record loaded from database (or initialized for new inserts)
2. New record values overwrite old values
3. System Validation Rules (If inserting Opportunity Products, Custom Validation Rules will also fire in addition to System Validation Rules)
4. All Apex before triggers (EE / UE only)
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. All Apex after triggers (EE / UE only)
9. Assignment rules
10. Auto-response rules
11. Workflow rules
12. Processes
13. Escalation rules
14. Parent Rollup Summary Formula value updated (if present)
15. Database commit
16. Post-commit logic (sending email)

16. Difference between database.query  and database.QueryLocator ?
Ans:
database.query allows you to make a dynamic SOQL query at runtime. You can build up a string and then use that as a query string at run time in the database.query.
it supports 50,000 records only.

database.getQueryLocator
returns a Query Locator that runs your selected SOQL query returning list that can be iterated over in batch apex.
it supports upto 50 million records.
If VF page have read only attribute, use Database.getQueryLocator().

17. What is Synchronous and Asynchronous ?
Ans:
Synchronous:
In a Synchronous call, the thread will wait until it completes its tasks before proceeding to next. In a Synchronous call, the code runs in single thread.

Example:


Trigger
Controller Extension
Custom Controller

Asynchronous:

In a Asynchronous call, the thread will not wait until it completes its tasks before proceeding to next. Instead it proceeds to next leaving it run in separate thread. In a Asynchronous call, the code runs in multiple threads which helps to do many tasks as background jobs.

Example:


Batch
@future Annotation

18. What is the difference between trigger.new and trigger.old?.When do use ?
Ans:
Trigger.new Returns a list of new version of sObject records.
Trigger.Old Returns a list of old version of sObject records.

trigger.new used in Insert and Update.
trigger.old used in Update and Delete.

No trigger.new in Delete.
No trigger.old in Insert.

– Trigger.Old is always readOnly
– We cannot delete trigger.new
– In before triggers, trigger.new can be used to update the fields on the same object.
– In After trigger, we get run time exception is thrown when user try to modify the fields in the same object.

19. How to restrict the trigger to Recursion?
Ans:
Trigger:
trigger updateTrigger on anyObject(after update) {
    if(checkRecursive.runOnce()) { 
      //write your code here
   }
}

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

20. How many methods are available in batch apex?
Ans:
The Database.Batchable interface contains three methods that must be implemented.
Start method:
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext ***bc***) {}

execute method:
global void execute(Database.BatchableContext ***BC***, list<P>){}

finish method:
global void finish(Database.BatchableContext ***BC***){}

21. Salesforce Governor limits.
Ans:
Total number of SOQL queries - 100
Total number of DMLs  - 150
Total number of records retrieved by SOQL - 50000
Total number of callouts  - 100 
Maximum number of batch Apex jobs in the Apex flex queue - 100
Maximum number of batch Apex jobs queued or active - 5

22. What is call-out and when we can use them?
Ans:
Apex Callouts enable Apex to invoke external web services.

Each callout request is associated with an HTTP method and an endpoint. The HTTP method indicates what type of action is desired.

GET Retrieve data identified by a URL.
POST Create a resource or post data to the server.
DELETE Delete a resource identified by a URL.
PUT Create or replace the resource sent in the request body.

GET the data from server

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for (Object animal: animals) {
        System.debug(animal);
    }
}

23. What is FUTURE method ?
Ans:
A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. You can also make use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error.

24. Difference between Public and Global in Salesforce?
Ans:
public
This means the method or variable can be used by any Apex in this application or namespace.
global
This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must also declare the class that contains it as global.

25. Have you used Offset in SOQL?
Ans:
The SOQL query normally returned 100 rows, you could use OFFSET 20 in your query to skip the first 20 rows and returns 21th row to 120th rows.

SELECT Name FROM Account WHERE Industry = 'Media' ORDER BY Name LIMIT 100 OFFSET 20

For example if there are 20 records then, if we specify offset as 10 in the query then it would return record 11 through 20.

OFFSET keyword can be used to implement pagination in visaulforce page tables.

26. Wrapper Class ?
Ans:
A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or collection of objects as its members
In the Visualforce most important use case is to display a table of records with a check box and then process only the records that are selected.

27. What is External ID ?
Ans:

External ID

Set the field as the unique record identifier from an external system.
You can have multiple records with the same external ID.

Unique ID field

This is a setting for the field that will prevent you from using the same value in multiple records for the unique field.

28. Exceptions in Apex ?
Ans:
SObjectException
CalloutException
DmlException
EmailException
LimitException
JSONException
ListException
NullPointerException
QueryException
StringException
TypeException
VisualforceException
RequiredFeatureMissing
NoSuchElementException
MathException
InvalidParameterValueException

29. SOQL query to get the deleted Rows also ?
Ans:
List<account> accs = [SELECT ID FROM account ALL ROWS];
System.debug(accs.size());

30. Delegate Administrative ?
Ans:
Use delegated administration to assign limited admin privileges to users in your org who aren’t administrators.


ICANN project Short Description:

ICANN (Internet Corporation for Assigned Names and Numbers) is US based a non-profit organization responsible for providing Domain name to the Requested Users.
Previously ICANN is using a Drupal system for managing the Requests raised for domain, We migrated that entire system to the Salesforce.Now when an end user requested for a domain from drupal system a Request will be created in Salesforce Org under Request object.Every Request is Related to a Domain(TLD Object in salesforce),Every TLD object is related to a Registry(Account object in salesforce),everyregistry will have Contact(Registry manager).there is a junction object which will relate many Registries to many registry managers.

Once an end user request for a domain an email will be sent to the Registry manager with request details including request Url in Community and end user details using Trigger.Registry manager can click on the link in the mail it will take them to Community there they will be able to see the all the requests and they can Accept those Requests or Decline those requests.

// prime numbers printing code
for(integer i=1;i<=90;i++)
{
integer count =0;
    for(integer j=1;j<=i;j++){
        if(math.mod(i,j)==0)
            count++;
    }
   // system.debug(count);
    if(count==2){
        system.debug(i);
    }
}

// num is prime or not checking
integer count =0;
for(integer j=1;j<=2;j++){
    if(math.mod(2,j)==0)
        count++;
}
if(count==2){
    system.debug('yes prime number');
}
else{
    system.debug('no not a prime number');
}


// displaying numbers from 100 to 1
for(integer i=0;i<100;i++)
{
    integer j=100-i;
    system.debug(j);  

}  


SDLC :

1.Planning
2..Designing
3. Building
4. Testing
5. Deploying

Tuesday, January 2, 2018

Restricting User to Double Click on Button in VF

This post is regarding to avoid one small issue I have come across it.
Let say there is a visual force page where input fields and one button is present. When that button is clicked records are inserted in to the object. If button is clicked twice in same time(double click) then records(duplicate records ) are being created twice. 

How will we avoid that?
How will restrict user to do double click on button?

Here I am sharing some snippet of code.Hope It will help you.

Page:

<apex:page standardController="Account">
    <apex:form >
        <apex:pageMessages id="messages"></apex:pageMessages>
        <apex:pageBlock title="Avoid Doublle Click" >
            <apex:pageBlockButtons location="both">               
                <apex:actionStatus id="saveStatus">                   
                    <apex:facet name="stop">
                        <apex:outputPanel >
                            <apex:commandButton action="{!save}" value="save" reRender="messages" status="saveStatus"/>
                            <apex:commandButton action="{!Cancel}" value="Cancel" immediate="true" />
                        </apex:outputPanel>
                    </apex:facet>
                    <apex:facet name="start">
                        <apex:outputPanel >
                            <apex:commandButton value="Saving..." disabled="true" />
                            <apex:commandButton value="Saving..." disabled="true" />
                        </apex:outputPanel>                       
                    </apex:facet>                   
                </apex:actionStatus>               
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Account Creating">
                <apex:inputField value="{!Account.Name}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>   
</apex:page>

Preventing Right Click,Copy,Paste in VF Page

Everybody must have visited bank site there we can not do right click or copy Account number and paste in another field Retype Account Number. That means we should not give any chance to anybody to see page source. We do this for more security purpose. 
That made me to think and try to design same in visual-force page. Here I have only used JavaScript for this functionality. 
There are some snippet of code.Hopefully It will help you. 

Functionality 

  • Preventing to see the Page Source.
  • Preventing paste Email field value in Re Email field.
Here is the page:-


<apex:page StandardController="Contact">
  <script>
      function DisableRightClick(event){    
        if (event.button==2)
        {
            alert("Right Click is not Allowed");       
        }
      }
     function DisableCtrlKey(e){
        
        var code = (document.all) ? event.keyCode:e.which;
         if (parseInt(code)==17){
            alert("Please re-type your email address");           
        }   
    }
  </script>
  <apex:form >
      <apex:pageBlock title="Create Contact" onmousedown="DisableRightClick(event)">
          <apex:pageBlockButtons >
              <apex:commandButton value="Save" action="{!save}"/>
          </apex:pageBlockButtons>
          <apex:pageBlockSection columns="1">
              <apex:inputField value="{!Contact.Firstname}"/>
              <apex:inputField value="{!Contact.LastName}"/>
              <apex:inputField value="{!Contact.Email}"/>
              <apex:inputtext value="{!Contact.Email}" label="Re-Type Email Id"  onKeyDown="DisableCtrlKey(event)"/>              
              <apex:inputField value="{!Contact.Phone}"/>              
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>

Visualforce Page Exactly Same as Contact Edit Page

The question was there will be a link called "Copy Mailing Address to Other Address" when clicked that link all Mailing address will be copied to other address same as standard edit page of contact.
This can be done two ways. 
  • By using java script
  • By using Controller extension
In the command link we have to call java script method there we will get all the field value of mailing addresss using documnet.getElementByid() method in javascript and will assign to the other address field. 

Second approach is we will call extension method where will assign all the mailing address field to other address field and will reRender (refresh) the block. It will behave exactly like as standard edit page layout of Contact functionality.
Now the challenge is how will we display that command link inside that pagablock section header.


This is the page and controller 


<apex:page standardController="Contact" extensions="contactEditPageExtension">
    <apex:sectionHeader title="Contact Edit" subtitle="New Contact"/>
    <apex:outputText value="Contacts not associated with accounts are private and cannot be viewed by other users or included in reports."> 
    </apex:outputText><br/><br/>
    <apex:form >
        <apex:pageBlock title="Contact Edit" id="test">
            <apex:pageBlockButtons location="both">
                <apex:commandButton value="Save" action="{!Save}"/>
                <apex:commandButton value="Save & New" />
                <apex:commandButton value="Cancel" action="{!Cancel}"/>
                
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Contact Information">
                <apex:inputField value="{!contact.FirstName}"/> 
                <apex:inputField value="{!contact.LastName}"/>       
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Test">
                   <apex:facet name="header">
                        <apex:pageBlockSectionItem >
                        <apex:outputText value="Address Information" style="float:left;"></apex:outputText>
                        <apex:commandLink value="Copy Malling Address to Other Address" style="float:right;" action="{!test}" reRender="test"/>
                        </apex:pageBlockSectionItem>
                    </apex:facet>
             
                    <apex:inputField value="{!contact.MailingCountry}"/> 
                    <apex:inputField value="{!contact.otherCountry}"/>  
                    <apex:inputField value="{!contact.MailingStreet}"/> 
                    <apex:inputField value="{!contact.otherStreet}"/>   
                    <apex:inputField value="{!contact.MailingState}"/> 
                    <apex:inputField value="{!contact.otherState}"/>    
                  
            </apex:pageBlockSection>
             
        </apex:pageBlock>
    </apex:form>
  </apex:page>



My controller 


public with sharing class contactEditPageExtension {
    public Contact contact{get;set;}
    public contactEditPageExtension(ApexPages.StandardController controller) {
        //this.contact = (Contact )controller.getRecord();
        contact = new Contact();
    }
    
    public void test(){
         contact.otherCountry  =  contact.MailingCountry;
        contact.otherState  =   contact.MailingState;
        contact.otherStreet  =   contact.MailingStreet;
        //return null;
    }


}

Add/Remove Functionality in a VF page pageblock table for Creating Multiple Records For a Particular Object.

I had come across a scenario where I was asked to develop some functionality where user can create list of records at a time(clicking on save button on one time) and can remove row.
Here I have created a pageblock table and there I am displaying 5 rows to enter data and there column, Name , Phone and Action. In Action column Delete link is present.When that link(Delete) is clicked then particular row will be removed. Two button is there Add Row and Save.
Add Row-->  When that button is clicked one more row will be created in the pagablock table
Save--> It will save the record.

Here is the page


<apex:page controller="creatingListOfRecordsController">
    <apex:form >
    
        <apex:pageBlock title="Creating List Of Account Records">
        <apex:pageMessages></apex:pageMessages>
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="Add Row" action="{!addRow}" reRender="table" immediate="true"/>
            </apex:pageBlockButtons>
                <apex:pageBlockTable value="{!accountwrapperList}" var="page" id="table"> 
                    <apex:column headerValue="Name">
                        <apex:inputField value="{!page.account.name}"/>
                    </apex:column>
                    <apex:column headerValue="Phone">
                        <apex:inputField value="{!page.account.Phone}" />
                    </apex:column>
                    <apex:column headerValue="Action">
                        <apex:commandLink value="Delete" action="{!removingRow}" immediate="true">
                            <apex:param name="index" value="{!page.counterWrap}"/>  
                        </apex:commandLink>
                    </apex:column>
                </apex:pageBlockTable>
                <apex:commandButton value="Save" action="{!saving}" />
            
        </apex:pageBlock>
    </apex:form>
</apex:page>

Here is the Controller


public with sharing class creatingListOfRecordsController {
    
    public list<Account> accountList{get;set;}
    public list<Accountwrapper> accountwrapperList{get;set;}
    public Integer counter{get;set;}
    
    public creatingListOfRecordsController(){
           counter = 0;
           accountList = new list<Account>(); 
           accountwrapperList = new list<Accountwrapper>();
           for(Integer i=0;i<5;i++){
               Accountwrapper actWrap = new Accountwrapper(new Account()); 
               counter++;
               actWrap.counterWrap = counter;
               accountwrapperList.add(actWrap); 
               
           }
       
    }
    
    public PageReference addRow(){
        //accountList.add(new Account());
        Accountwrapper actWrap = new Accountwrapper(new Account()); 
        
        counter++;
        actWrap.counterWrap = counter; 
        accountwrapperList.add(actWrap); 
        return null;    
    }
    public PageReference removingRow(){
    
        Integer param = Integer.valueOf(Apexpages.currentpage().getParameters().get('index'));
        
        for(Integer i=0;i<accountwrapperList.size();i++){
            if(accountwrapperList[i].counterWrap == param ){
                accountwrapperList.remove(i);     
            }
        }
        
        
        counter--;
        return null;    
    }
    
    public PageReference saving(){
        list<Account> updateAccountList;
        updateAccountList = new list<Account>();
        if(!accountwrapperList.isEmpty()){
            for(Accountwrapper accountWrapper:accountwrapperList){
                updateAccountList.add(accountWrapper.account);
            }
        }
        if(!updateAccountList.isEmpty()){
            upsert updateAccountList;
        }
       ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Record Saved Successfully.');
       ApexPages.addMessage(myMsg); 
        return null;
    }
    
    public class Accountwrapper{
        public Account account{get;set;}
        public Integer counterWrap{get;set;}
        
        public Accountwrapper(Account act){
            this.account = act;  
             
        }
    }
    
}
The out put will be exactly like this image 

Encryption and Decryption In Salesforce.

Encryption, is the process of changing information in such a way as to make it unreadable by anyone except those possessing special knowledge (usually referred to as a "key") that allows them to change the information back to its original, readable form.
To encrypt some value we have to use some key value that can be hard coded or we can generate key also by using this 

Blob cryptoKey = Crypto.generateAesKey(256);
We have to use same key to decrypt that value.

Here I am going to share some code.Hope it will help you. I have created one visualforce page and one controller. In the page only one field(Name) is there and two button(Save & Update).
When some value is entered in the name field and clicked on save button that value will be stored in the object encrypted format.
Now record id in the url and click on update button encrypted value will be converted in to original format.


Here is my page  


<apex:page standardController="Account" extensions="EncryptionandDecryptionExtension">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:inputField value="{!encrypt.Name}"/>
                <apex:commandButton value="Save" action="{!Save}"/>
                <apex:commandButton value="Update" action="{!test}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form> 
</apex:page>

Here is My Controller 


public class EncryptionandDecryptionExtension {
    public account encrypt{get;set;}
    //Blob cryptoKey;
    Blob cryptoKey = Blob.valueOf('380db410e8b11fa9');
    public Id recordId{get;set;}
    public EncryptionandDecryptionExtension(ApexPages.StandardController controller) {
        //cryptoKey = Crypto.generateAesKey(256);
        recordId = Apexpages.CurrentPage().getParameters().get('id');
        if(recordId !=null){
            encrypt = [SELECT id,Name From account 
                       WHERE id=:recordId];
        }
        else{
            encrypt = new account();
        }
    }
    
    public PageReference Save(){
        
        Blob data = Blob.valueOf(encrypt.Name);
        Blob encryptedData = Crypto.encryptWithManagedIV('AES128', cryptoKey , data );
        String b64Data = EncodingUtil.base64Encode(encryptedData);
        encrypt.name = b64Data ;
        
        insert encrypt;
        return null; 
    }
    public PageReference test(){
        
        //Blob cryptoKey = Crypto.generateAesKey(256);
        //Blob data = Blob.valueOf(encrypt.Name);
        Blob data = EncodingUtil.base64Decode(encrypt.Name);
        Blob decryptedData = Crypto.decryptWithManagedIV('AES128', cryptoKey , data);
        String dryptData = decryptedData.toString();
        System.debug('Printing dryptData '+dryptData);
        
        encrypt.name = dryptData;
        
        update encrypt;
        return null; 
    }
}