Friday 31 July 2015

Sort values in Custom Multi Select Picklist - Visual force Page

Hi Friends ,

Here I am giving the post to sort the values in Multi Select Picklist . I am giving the simple technique to sort values using Java Script in VF Pages.

Here is the sample code to include in VF page to sort pick list values,


function sortRightSelect(typeval) {
    selElem = document.getElementById(typeval);
    var tmpAry = new Array();
    for (var i=0;i<selElem.options.length;i++) {
        tmpAry[i] = new Array();
        tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][1] = selElem.options[i].value;
    }
    tmpAry.sort();
    while (selElem.options.length > 0) {
        selElem.options[0] = null;
    }
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElem.options[i] = op;
    }
    return;
 }

Here is the sample code to call in OnChange function :

sortRightSelect('tehpage:theform:thepb:accright');

Here the highlighted code in red color is the ID value for the PicklIst value from VF page.


Thank you.



Monday 27 July 2015

No More Data Staging and Power of Batch Apex in salesforce

Data Staging :

A staging area, or landing zone, is an intermediate storage area used for data processing during the extract,
transform and load (ETL) process. The data staging area sits between the data source(s) and the data target(s),
which are often data warehouses, data marts or other data repositories.

In salesforce , we may need data stagging some times before completely process the data from out side and to insert into salesforce objects.

Scenario :

In some situations , we may need to upload large volume of data using file upload process , review the data before process and then upload the data in to salesforce objects.
When processing large volume of the records in apex, some time apex can hit governor limits .

Governors and Limits

Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces limits to ensure that
runaway Apex doesn’t monopolize shared resources. If some Apex code ever exceeds a limit,
the associated governor issues a run-time exception that cannot be handled.


Power of Batch APEX :

1.Will this works on millions of records ?
Yes batch apex are asynchronous process and can support upto 50 million records and hence for 1 million this code will run

2.Does Force.com run time calls the "execute" method each time with 50k records
You will specify batch size while you invoke batch .Say i specify batch size as 400.Then 50000/400 number of batches will run.In each batch context 400 records will picked .

3.Does the execute method has a time-out after X seconds?
No there are no time outs.There is some time out limit 60000 milliseconds of CPU time for async transactions.

4.Can we control the amount of records being delivered to the "execute" method? (for example if we wish to deliver each time 500 contacts)
Yes we can control this through the scheduler script by specifying the batch size

    String query = 'select Id from Contact'
    ManageRecords batchpr = new ManageRecords (query);
    Id batchprocessId = Database.executeBatch(batchpr,500);
The above script that you have i have split and 500 is my batch size .

Batch Apex Skeleton :

global class SearchAndReplace implements Database.Batchable<sObject>{

   global final String Query;

   global final String Entity;
   global final String Field;
   global final String Value;

   global SearchAndReplace(String q, String e, String f, String v){


      Query=q; Entity=e; Field=f;Value=v;

   }

   global Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope){

     for(sobject s : scope){
     s.put(Field,Value); 
     }
     update scope;
    }

   global void finish(Database.BatchableContext BC){

   }
}


Batch Apex & Data Staging :

There is simple trick to avoid the apex governor limits and process the larger amount of records in to salesforce objects from staging .
Batch apex simplifies this staging mechanism in salesforce and it no more requires staging tables before process the data to salesforce objects.

the only thing you need to do is , prepare data and send it to batch apex to process .

Below is the small example :

global class BatchProcessStaggingsdata implements Database.Batchable<ManageRecords.Contactsstagging>{
   global final list<ManageRecords.Contactsstagging> LstStaggingData;
   global final string strSummarylogId ;
   global integer ibatchCount =1;
   global BatchProcessStaggingsdata(list<ManageRecords.Contactsstagging> LstSelectedStaggingData){
     LstStaggingData=LstSelectedStaggingData;
   }
   global list<ManageRecords.Contactsstagging> start(Database.BatchableContext BC){
      return LstStaggingData;
   }
   global void execute(Database.BatchableContext BC, List<ManageRecords.Contactsstagging> scope){
     system.debug('******LstData'+scope);
     
   }
   global void finish(Database.BatchableContext BC){
     
     
   }
}

In the above process , LstSelectedStaggingData holds the staging data and assigning to a list in the batch apex.

Thank you
Haribabu Amudalapalli

Wednesday 8 July 2015

JSON Parse Error - Unexpected Token

Hi Floks ,


When we are trying to parse the data , which are coming from Apex ,some time we may experience the following issue,

      JSON Parse Error - Unexpected Token

Code snippet :


     Var JSONVal = '{!StrJONdata}' // Apex string using to parse the data.     var ParsedData = JSON.parse(JSONVal );


In the above scenario , some times you may experince above error.Please use JSENCODE tag to format the string ,


Code snippet :


var JSEncode = '{!JSENCODE(strJSON)}';var lstVOCQustns = JSON.parse(JSEncode);


Thanks 

Visualforce Remote Objects - Salesforce Developers

When you dabble in code, every day is an adventure and opens a window of new opportunities to experiment and challenges. The mantra of the codingFINAL TRAIN IMAGEgame is to keep oneself ahead of the game and have that extra edge. Therefore, today we would like to introduce to you the concept of Visualforce Javascript Remoting which is a technique within Salesforce to call methods in a class via Javascript.
If this has got you wondering how it will help, here are top 3 reasons that answer your why:
Need for Speed – Of course, remoting will help you set up the fastest way of calling controller code and passing data back and forth from the page.
Freedom from Forms – The good news is that you don’t have to use forms whether it is Apex or anything else. What is helpful is that you do not have to pass or store all the data for the controller calls!
Being ahead of the game – The third reason is perhaps the best because remoting helps you be asynchronous. Through this you can start loading data for pages the user has not even accessed yet!
Now, let us see what is JavaScript remoting all about:
1. The remote method invocation you add to the Visualforce page is written in JavaScript.
2. The remote method definition is written in Apex, but there are few differences from normal action methods.
3. The response handler callback function you add to or include in your Visualforce page is written in JavaScript.
Here’s how it is done:
Page JavaScript:
<script type=”text/javascript”>
function getRemoteAccount() {
var accountName = document.getElementById(‘acctSearch’).value;
Visualforce.remoting.Manager.invokeAction(
‘{!$RemoteAction.MyController.getAccount}’,
accountName,
function(result, event){
if (event.status) {
// Code for callback handling
}
}, {escape: true}
);
}
</script>
Controller:
@RemoteAction
global static String getItemId(String objectName) { … }

VF Remote Objects
What are VF remote objects? Visualforce Remote Objects are proxy objects that allow basic DML operations on sObjects directly from JavaScript.
How do the JavaScript remote objects help? Remote Object controller work wonders by sharing rules, field level security and data accessibility concerns.
Using Visualforce Remote Objects consists of two parts:
1. Defining Remote objects.
2. Data access functions are written in JavaScript which use the proxy objects made available by the access definitions to perform create, select, update, and delete operations on your data.
Here’s how we define remote objects which specify objects and fields to make accessible on the page:
Syntax:
<apex:remoteObjects >
<apex:remoteObjectModel name=”Warehouse__c” jsShorthand=”Warehouse” fields=”Name,Id”>
<apex:remoteObjectField name=”Phone__c” jsShorthand=”Phone”/>
</apex:remoteObjectModel>
</apex:remoteObjects>
<apex:remoteObjects>
Use this component, along with child and components, to specify the sObjects and fields to access using Visualforce Remote Objects.
<apex:remoteObjects>
Defines an sObject and its fields to to create accessibility using Visualforce Remote Objects. This definition can include a shorthand name for the object, which you can use in JavaScript instead of the full API name. This is especially useful if your organization has a namespace or if you’re packaging an app, and it helps make your code more maintainable.
<apex:remoteObjectField>
Defines the fields to load for an sObject. Fields defined using this component, instead of the fields attribute of , can have a shorthand name, which allows the use of a “nickname” for the field in client-side JavaScript code, instead of the full API name. Use as child of .
Methods:
Retrieving records:
var wh = new SObjectModel.Warehouse();
wh.retrieve({ limit: 10 }, function(err, records){
if(err) alert(err.message);
else {
// Code to display records
}
Retrieve records with where condition:
var src = new SObjectModel.getActs();
src.retrieve({ limit : 10,
where : { cType :{eq : ‘Banking’}}
} ,
function(err,records){
if(err == null)
{
//Process returned “records” to display in Visualforce code.
}
} );
Save record:
var record = new SObjectModel.Account({
Id: id,
BillingState: stateVal ,
Phone: PhoneVal ,
});
record.update(Dataload);
Delete Record:
var AccountTodelete= new SObjectModel.Account();
AccountTodelete.del(id,Dataload);
Create Record:
var recordToinsert = new SObjectModel.Account({
Name: Nameval,
BillingState: stateVal ,
Phone: PhoneVal ,
});
recordToinsert.create(Dataload);

Important Notes:
1. Remote Objects respects your organization’s field level security settings. The fields that aren’t accessible to the person viewing the page appear blank. Actions that modify field data (create(), update(), and upsert()) fail with an error if they include inaccessible fields in the request.
2. Remote Objects use an object to specify criteria for retrieve() operations. Use this object to specify where, limit, and offset conditions for your queries.
The structured format of the query object enables Visualforce to validate the criteria at save time which reduces the likelihood of runtime errors.
var ct = new RemoteObjectModel.Contact();
ct.retrieve(
{ where: { FirstName: {eq: ‘Marc’},LastName: {eq: ‘Benioff’} },
orderby: [ {LastName: 'ASC'}, {FirstName: 'ASC'} ] limit: 1 },
function(err, records) {
if (err) {
alert(err);
} else {
}
}
);
The query criteria finds a contact named Marc Benioff and limits the query to a single result.
where Conditions:
where conditions enable you to filter the results of a retrieve operation, much the same way that a WHERE condition in a SOQL query does. The operators that are available for where conditions are:
eq: equals
ne: not equals
lt: less than
lte: less than or equals
gt: greater than
gte: greater than or equals
like: string matching. As with SOQL, use “%” as a wildcard character.
in: in, used for finding a value that matches any of a set of fixed values. Provide values as an array, for example, ['Benioff', 'Jobs', 'Gates'].
nin: not in, used for finding a value that matches none of a set of fixed values. Provide values as an array, for example, ['Benioff', 'Jobs', 'Gates'].
and: logical AND, used for combining conditions
or: logical OR, used for combining conditions
Within the where object, add field name and condition pairs to create complex criteria. Multiple conditions by default are treated as AND conditions. For example:
{
where:
{
or:
{
FirstName: { like: “M%” },
Phone: { like: ‘(415)%’ }
}
}
}
orderby Conditions
orderby enables you to set a sort order for your results and facilitates sorting up to three fields. Specify your orderby conditions as an array of JavaScript objects that contain name-value pairs. The field to sort on is the name, and the sort description is the value. The sort description enables you to sort ascending or descending and to sort null values first or last. For example:
orderby: [ {Phone: "DESC NULLS LAST"} , {FirstName: "ASC"} ]
limit and offset Conditions
limit and offset enable you to retrieve a specific number of records at a time and to page through an extended set of results.Use limit to specify how many records to return in one batch of results. The default value is 20. The maximum is 100.Use offset to specify how many records to skip in the overall result set before adding records to the returned results. The minimum is 1. There is no maximum limit.
This was the third edition from our series on “Apex programming tips and tricks” – Keep experimenting and reinventing!
Categories: Programming in Apex

Hari

Hari Amudalapalli currently works as Sr.Software engineer with AppShark. He is a Salesforce certified Force.com Advanced Developer and holds an experience of 5 years. He is fond of reading informative articles and playing cricket when time permits!

ZAP tool

How well protected are your web applications? With hacking incidents and data leakage on rise, it is nowPicture3 more important than ever to ask yourself this question. Hence, security testing is the perfect antidote to fixing the vulnerabilities found in web applications.
ZAP (Zed Attack Proxy) is one such open source tool used for integrated penetration testing done by developers and functional testers. An easy to use and simple tool, it offers automated scanners and a set of tools which allow you to find security vulnerabilities manually.
Important features:
Quick Start
It offers you an easy way to quickly test a web application. Enter the URL of your target application and press the ‘Attack’ button.

1
Sites Tab
It shows all of the URLs visited – Select any of the nodes in the tree to display the request and response for that URL in the relevant tab.
2

Request Tab
It shows the data sent by your browser for the request highlighted in either the Sites or History tab.
3
Response Tab
It shows the data sent to the browser for the request highlighted in either the Sites or History tab.
4

Break Tab
It allows you to change a request or response when it has been caught by ZAP via a breakpoint.  The elements which can be changed are : The header, hidden fields, disabled fields.
While the Break tab is not in use it will be in grey colour: X
When a break point is hit the tab icon is changed to a red cross: :X
5
History Tab:
It shows a list of all requests in the order which they were made. For every request, you can see:
The request index – Each request is numbered, starting at 1
The HTML method, e.g. GET or POST
The URL requested
The HTTP response code
A short summary of what the HTTP response code means
The length of time the whole request took.
Any Alerts on the request.
Any Notes you have added to request
Any Tags on the request
6

Search Tab
It allows you to search for regular expressions in all of the URLs, requests, responses, headers and fuzz results.
7
Break Points tab
It shows all the break points that you have set. It can be set via the History and Sites tabs as well as the ‘Add a custom HTTP break point’ button on the top level toolbar.
8
 Alerts tab
It shows the Alerts that have been raised in this session.Double clicking an alert will display the ‘Add Alert dialog’ which will allow you to change the alert details.
 9
Active Scan tab
It allows you to perform an active scan on any of the sites that have been accessed.
10
Spider tab
It shows you a set of unique URIs found by the Spider during the scans.The toolbar provides a set of buttons which allow you to start, stop, pause and resume the scan. A progress bar shows how far the scan of the selected site has progressed.
For each request you can see:
Processed – Whether the URI was processed by the Spider or was skipped from fetching because of a rule (e.g. it was out of scope)
Method – The HTTP method, e.g. GET or POST, through which the resource should be accessed
URI – the resource found
Flags – any information about the URI (e.g. if it’s a seed or why was it not processed)
11
Fuzzer tab
The Fuzzer tab shows you the requests and responses performed when you fuzz a string.

Params tab
This shows a summary of the parameters a site uses. Sites can be selected via the toolbar or the Sites tab.

 12


Http Sessions tab
This tab shows you the set of identified HTTP sessions for each Site, as detected by the HTTP Sessions extension.
13

Active Scan Rules
This rule checks the headers of secure pages and reports an alert if they allow a browser to cache the page.
14


AJAX Spider tab
The AJAX Spider tab shows you the set of unique URIs found by AJAX Spider:
15
WebSocket tab
The WebSockets tab displays all messages from WebSocket connections. While ZAP is active, visit e.g.: Mozilla’s Browser Quest to see WebSockets in action.
16
Forced Browse tab
The Forced Browse tab allows you to perform a browse scan on any of the sites that have been accessed.
17






Categories: General

Hari

Hari Amudalapalli currently works as Sr.Software engineer with AppShark. He is a Salesforce certified Force.com Advanced Developer and holds an experience of 5 years. He is fond of reading informative articles and playing cricket when time permits!

Tuesday 7 July 2015

window.showModalDialog deprecated

Hi FOLKS, 

This feature is going away. Please fix your Web sites and applications.
Support has been removed in Chrome 37. But they have  added a temporary Enterprise Policy setting to re-enable showModalDialog. This showModalDialog() method was removed completely in Chrome 43.
Mozilla has announced that it will remove support for this method (bug 981796). Regarding timing, it shouldn't be before Firefox 39. This means that the function will be around until around mid-June 2015. It also means that for enterprise you can switch to using ESR 38 builds, which will have the function into mid 2016.

Salesforce Applications :

Use the following simple steps to resolve the issues ,

1.  Replace your Showmodal dialog with Window.open Tag .
2. Include following code in Popup page to send parameters to Parent window JS function from Pop up window ,

Here we are preparing JSON string to send all the required parameters to Parent window as below,

var OrderProducts = new Array();
var jsonText ;
function Addproducts() 
 {
// Prepare JSON Data with parameters , you want to send to parent JS function
              var products = new Object();
products.ProdName = 'TEST Product';
products.prodid = 'Test Id'
OrderProducts.push(products);
jsonText = JSON.stringify(OrderProducts);

       // This is the function from Parent window and add parameters to send .
window.opener.openProducts(jsonText); (openProducts() is the JS function in Parent window)
 
// Closing the console
        self.close();
}

3.  Following is the JS function from Parent window ,

function openProducts(jsonstring){
       alert(jsonstring);
}

Above sample steps will provide solution for the issues related to window.showmodaldailogs.

Thank you.