• sfdc-L
  • NEWBIE
  • 0 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 35
    Questions
  • 12
    Replies

Hi,

i am facing issue as given below scenario.
Current functionality is uploading the data in to custom object by using custom page i.e. 5k records,its working fine.
Requirement is need to upload 10k records,but when i was changed the query limit to 10000,getting below error

"Too many code statements: 200001
Error is in expression '{!readFile}' in component <apex:commandButton> in page svc_bidassetcsvuploadutility

An unexpected error has occurred. Your development organization has been notified."

i belive its throwing the error in insertBIdAssetRecords method but not able to find where do i optmaized the code,so here i am posting my code and i request you to verify it and make any changes if needed.Help is greatly appreciated

VF Page
---------
<apex:page sidebar="false" controller="Svc_BIdAssetCsvUploadUtility" tabStyle="B_SerialNumber__c">
<apex:form >
<apex:sectionHeader title="Upload data Assets"/>
<apex:pagemessages />
<apex:pageBlock >
<apex:pageblocksection columns="1" title="Upload CSV">
<apex:pageBlockSectionItem >
<font color="red"> <b>Please use the standard template to upload Id Asset records. <a href="{!templateUrl}" target="_blank"> Click here </a> to download the template. </b> </font>
<br/> <b>Maximum {!RECORD_PROCESSING_LIMIT} records can be inserted in every load.</b>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:inputFile value="{!fileContentBlob}" filename="{!fileName}" accept="csv" alt="Browse the file to upload"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:commandButton action="{!readFile}" value="Upload" id="theButton" style="width:70px;"/>
</apex:pageBlockSectionItem>
</apex:pageblocksection>
<apex:pageblocksection columns="1" title="Results" rendered="{!NOT(ISNULL(insertedRecords))}">
<apex:pageBlockSectionItem >
<apex:outputText style="font-weight:bold" value="Success: {0} records">
<apex:param value="{!successCount}"/>
</apex:outputText>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText style="font-weight:bold" value="Error: {0} records">
<apex:param value="{!errorCount}"/>
</apex:outputText>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputPanel ><b>For more details download results</b><apex:commandLink action="{!downloadCsv}" value="here" id="theCommandLink"/></apex:outputPanel>
</apex:pageBlockSectionItem>
</apex:pageblocksection>
</apex:pageBlock>
</apex:form>
</apex:page>
---------------------------------------------------
Controller:
/* ==============================================================================
Name : Svc_BIdAssetCsvUploadUtility
Description : Controller class to reads a CSV file and insert Id-Asset records
================================================================================= */
public class Svc_BIdAssetCsvUploadUtility{
private List<ResultWrapper> displayResults;
private String tempalteName = 'BId-Asset Template';
private String templateId;
public transient String fileName{get;set;}
public transient Blob fileContentBlob{get;set;}
public transient Integer errorCount{get;set;}
public transient Integer successCount{get;set;}
public Integer RECORD_PROCESSING_LIMIT{get{return 10000;} private set;}

/*==========CONSTRUCTOR==========*/
public Svc_BIdAssetCsvUploadUtility(){}

/*=============================================================================================
Description : Method to read data from uploaded CSV file and then insert Id-Asset records.
===============================================================================================*/
public Pagereference readFile(){
try{
errorCount = 0;
successCount = 0;
displayResults = new List<ResultWrapper>();

if(fileContentBlob == Null || fileName == Null){
String errorStr = 'Please select a CSV file.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
}
if(!fileName.endsWithIgnoreCase('.csv')){
String errorStr = 'Only CSV files can be processed.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
}

String fileContentStr = fileContentBlob.toString();
List<List<String>> allRecords = parseCSV(fileContentStr,true);

if(allRecords.size() == 0){
String errorStr = 'Uploaded file contains no records.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
} else if(allRecords.size() > RECORD_PROCESSING_LIMIT){
String errorStr = 'You are trying to process ' + allRecords.size() + ' records. Maximum ' + RECORD_PROCESSING_LIMIT + ' records can be processed.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
}


Map<String, String> mapAssetPartNameToId = fetchAssetIds(allRecords);
insertBIdAssetRecords(allRecords, mapAssetPartNameToId);

} catch (Exception e) {
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,e.getMessage());
ApexPages.addMessage(errormsg);
}
return null;
}

/*=============================================================================================
Description : Method to insert Id-Asset records.
@params : List<List<String>> allRecords - comma separated values for uploaded records
@params : Map<String, String> mapAssetPartNameToId - Map with Key=>AssetName and Value=> AssetId
@return : void
Modification History:
===============================================================================================*/
private void insertBIdAssetRecords(List<List<String>> allRecords, Map<String, String> mapAssetPartNameToId){
String partAssetName;
displayResults = new List<ResultWrapper>();
List<BId_SerialNumber__c> bId_AssetsToInsert = new List<BId_SerialNumber__c>();

for (Integer count = 0; count < allRecords.size(); count++){
List<String> fieldValues = allRecords.get(count);

ResultWrapper wrapper = new ResultWrapper();
wrapper.serialNumber = fieldValues.get(0).trim();
wrapper.pdtName = fieldValues.get(1).trim();
wrapper.bId = fieldValues.get(2).trim();

B_Id__c tempBId = new B_Id__c();
if(fieldValues.get(2).trim().isNumeric()){
tempBId.B_Id__c = Integer.valueOf(fieldValues.get(2).trim());
} else {
wrapper.notes = 'Id should be a numeric value';
}

BId_SerialNumber__c record = new BId_SerialNumber__c();
record.Asset__c = mapAssetPartNameToId.get(fieldValues.get(0).trim() + ',' + fieldValues.get(1).trim());
record.B_Id__r = tempBId;

bId_AssetsToInsert.add(record);
displayResults.add(wrapper);
}

if(bId_AssetsToInsert.size() > 0){
List<Database.SaveResult> saveResults = Database.insert(bId_AssetsToInsert, false);

Integer index = 0;
for(Database.SaveResult result : saveResults){
if(result.isSuccess()){
displayResults.get(index).bIdAst = result.getId();
displayResults.get(index).status = 'Success';
successCount++;
} else {
//Avoid over writing the custom error messages
if(String.isBlank(displayResults.get(index).notes)){
displayResults.get(index).notes = result.getErrors().get(0).getMessage();
}
displayResults.get(index).status = 'Error';
errorCount++;
}
index++;
}
}
}

/*=============================================================================================
Description : Method to query Asset records based on the Serial Numbers
===============================================================================================*/
private Map<String, String> fetchAssetIds(List<List<String>> allRecords){
Map<String, String> mapAssetPartNameToId = new Map<String, String>();
String baseQryStr = 'SELECT Id,Product2.Name,SerialNumber FROM Asset WHERE SerialNumber IN ';
String whereClause = '';

//Rows with BLANK values should not be included in query
for(List<String> fieldValues : allRecords){
if(String.isNotBlank(whereClause) && String.isNotBlank(fieldValues.get(0).trim())){
whereClause += ',\''+ fieldValues.get(0).trim() + '\'';
} else if(String.isNotBlank(fieldValues.get(0).trim())){
whereClause = '\''+ fieldValues.get(0).trim() + '\'';
}
}

String qryStr = baseQryStr + '(' + whereClause + ')';
List<Asset> listAssets = Database.query(qryStr);
for(Asset ast : listAssets){
mapAssetPartNameToId.put((ast.SerialNumber.trim() + ',' + ast.Product2.Name.trim()), ast.Id);
}

return mapAssetPartNameToId;
}

/*=============================================================================================
Description : Method to download load result in an excel file
===============================================================================================*/
public Pagereference downloadCsv(){
Pagereference pgRef = new Pagereference('/apex/Svc_BIdAssetCsvUploadResults');
pgRef.setRedirect(false);
return pgRef;
}

/*=============================================================================================
Description : Method to create url that points to standard template to load Id-Asset records
===============================================================================================*/
public String getTemplateUrl(){
If(templateId == Null){
List<Document> listDocuments = [Select Id from Document where Name = :tempalteName];

If(listDocuments.size() == 1){
templateId = listDocuments.get(0).Id;
}
}

return URL.getSalesforceBaseUrl().toExternalForm() + '/servlet/servlet.FileDownload?file=' + templateId;
}

/*=============================================================================================
Description : Method to prepare data to download in excel
===============================================================================================*/
public List<List<ResultWrapper>> getInsertedRecords(){
if (displayResults != null && displayResults.size() > 0){
List<List<ResultWrapper>> listResultLists = new List<List<ResultWrapper>>();
List<ResultWrapper> listResults = new List<ResultWrapper>();

ResultWrapper header = new ResultWrapper();
header.serialNumber='<b>Serial Number</b>';
header.pdtName='<b>Product Name</b>';
header.bId='<b>BId</b>';
header.bIdAst='<b>BIdAsset</b>';
header.notes='<b>Notes</b>';
header.status='<b>Status</b>';

listResults.add(header);
Integer count = 1;
for(ResultWrapper result : displayResults){
listResults.add(result);
count++;
if(Count == 1000){ //SFDC limit to display 1000 results on a visualforce page
listResultLists.add(listResults);
listResults = new List<ResultWrapper>();
count = 0;
}
}

if(listResults.size() != 0){
listResultLists.add(listResults);
}
return listResultLists;
}else {
return null;
}
}

=============================================================================================
Description : Method to parse CSV data
Comma separated values of uploaded CSV
===================================================
public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {
List<List<String>> allFields = new List<List<String>>();

// replace instances where a double quote begins a field containing a comma
// in this case you get a double quote followed by a doubled double quote
// do this for beginning and end of a field
contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
// now replace all remaining double quotes - we do this so that we can reconstruct
// fields with commas inside assuming they begin and end with a double quote
contents = contents.replaceAll('""','DBLQT');
// we are not attempting to handle fields with a newline inside of them
// so, split on newline to get the spreadsheet rows
List<String> lines = new List<String>();

lines = contents.split('\n');

Integer num = 0;
for(String line: lines) {
// check for blank CSV lines (only commas)
if (line.replaceAll(',','').trim().length() == 0) continue;

List<String> fields = line.split(',');
List<String> cleanFields = new List<String>();
String compositeField;
Boolean makeCompositeField = false;
for(String field: fields) {
if (field.startsWith('"') && field.endsWith('"')) {
cleanFields.add(field.replaceAll('DBLQT','"'));
} else if (field.startsWith('"')) {
makeCompositeField = true;
compositeField = field;
} else if (field.endsWith('"')) {
compositeField += ',' + field;
cleanFields.add(compositeField.replaceAll('DBLQT','"'));
makeCompositeField = false;
} else if (makeCompositeField) {
compositeField += ',' + field;
} else {
cleanFields.add(field.replaceAll('DBLQT','"'));
}
}

allFields.add(cleanFields);
}
if (skipHeaders) allFields.remove(0);
return allFields;
}

//Wrapper class representing result of inserted records.

public class ResultWrapper{
public String serialNumber{get;set;}
public String pdtName{get;set;}
public String bId{get;set;}
public String bIdAst{get;set;}
public String notes{get;set;}
public String status{get;set;}
}
}
I would look forward to your reply... :)

  • September 26, 2013
  • Like
  • 0

Hi Team,

 

i have 2 custom fileds  i.e startdate and enddate and data type is date/time .so i need a formula as mentioned below scenario

formula is startdate+enddate*8

ex:startdate is friday 9 am and endate is monday 5 pm so if i calculate as per above formula getting 32 hours

but my requirement ,it should not caculate satarday and sunday so the result will be 16 hours

Pls let me know asap.

 

Thanks!

  • December 07, 2012
  • Like
  • 0
Hi all, i have picklist month field wich contains numeric values and year also i have picklist field.Lets say this year when you enter month i.e. Nov or Dec and year i.e. 2012 then it should not allow.So it should allow only month i.e Oct and year i.e.2012 (i.e.Current year of the previous month). Fields:month__c and Year__c Pls provide the example and let me know asap Thanks!
  • November 08, 2012
  • Like
  • 0
Hi all, how do i display the custom reports by tabs .but i didn't create any vf page for this and simply i have created custom report and i want to display the reports by tabs .Even i have tried using web tab i.e. pasting the url but it displaying along with showheader and it is not looking good. so pls let me know the solution asap Thanks!
  • November 08, 2012
  • Like
  • 0

hi all

 

in the batch apex sheduler,i did n't provide system.scheduler like data and time,i have mentioned as manually such as follows,

 

batchapexscheduler:

----------------------------

sambatchapexscheduler  testbas=new sambatchapexscheduler();

database.executebatch(testbas,200);

 

so how do i write test class for above and please let me know asap

Thanks!

 

  • October 11, 2012
  • Like
  • 0
HI team, As we know that we have dynamic pciklist for permission set by using apex coding. But same thing i was trying add (multi select) picklist for permission set, so how can i achieve this funtionality.i have given below example for dynamic picklist for permission set.So please let me know the solution with best example. public List getItems() { options.add(new selectOption('--Choose PermissionSet--')); for(PermissionSet name:[select Name from PermissionSet where is OwnedByProfile=false order by Name] ) { options.add(new selectOption(name.id,name.Name)); } } Thanks!
  • September 18, 2012
  • Like
  • 0
Hi team, i have apexpageblock table so in that displaying set of columns,in that i have 1 row and having many contents, so i want to display in single row and making it horizontal very wide.so kindly let me know with suitable example asap. Thanks
  • August 08, 2012
  • Like
  • 0

hi all,

 

how do i fetch records from permissionsetAssignment id in user object? and how do i query to fetch the list of permissisonsetAssignments that assigned to the perticuler user?let me asap.

 

Thanks!

  • August 06, 2012
  • Like
  • 0
Hi all, how do i query userlicense name from user object?i need to list out the users name based on the user license (ex:Userlicense ='Salesforce') .pls provide with suitable example asap Thanks
Hi all, i dont want to write a soql query in forloop because it bypass the governor limits .so how can i write the soql outside of the forloop.so kindly let me know asap. String[] ps= new String[]{}; public String[] getUserLicense() { return ps; } public void setUserLicense(String[] ps) { this.ps = ps; } public List getItems() { List op = new List(); for(UserLicense p : [SELECT Id, Name FROM UserLicense]) op.add(new SelectOption(p.Id, p.Name)); return op; } == vf: THanks
Hi all, It is possible to create an application to clone an inbound changeset to an outbound changeset .kindly let me any possiblities and provide me description with deails asap Thanks!
Hi all, we can embed a visual workflow in visualforce page? and i want to visual workflow to be displayed in the webpage.please let me know whether it is possbile or not? Thanks!
HI all, we know that lenth of encrypted text is 175 ,whether it is possible to increase the length for encrypted text?if possible then please give some suggestion asap. Thanks!
HI Team, i have a class that implements shedulable and this class is used to send a mails,also i have test class for this shedulable,when we deploy from sandbox to prod getting error'System.unexpectedException:No more than one executeBatch can be called within a test method'.I came to know that shedule is invoking 2 times i.e in class and test class . my code was like this ex: eventreminderbatch erb=new eventreminderbatch(); String schr='0 17?2011-2012'; System.shedule('eventreminderbatch ',schr,erb); So how to resolve this issue during the deployment process pls let me know asap. Thanks!
HI all, i have scenario like,1 custom object and 2 custom fields i.e. username_c and password__c so i am storing the password in custom object. so what i want is ,whatever storing the password in custom object that wants to be return by using apex class.i was tring to return but i am not getting so pls relsove this issue.but i am not using any vf page. public with sharing class Sample { public static string registerUser() { List obj = new List(); obj = [Select Username__c,Password__c from Login__c where Username__c =:id Limit 1]; return password__c; } THnaks
HI team, i was facing thsi issue in sites,we developed a vf page and when we click the id it will redirect to detaile page and related list.so in related list when i am editing the pericular record its throwing error i.e. unAutherized in the sites.so how do i reslove this issue let me know asap. Thanks!
Hi team, In summary report i want to calculate avg .my issue was if we have null values rows even though its considering in avg.but i dont want to add null values so how can i avoid this and let me know if you have sample formula. Thanks
Hi all, As we know that how trigger execution works but same thing i want to know how apex class execution works i.e. including test classes and when test classes fails.so kindly let me know asap Thanks!

Hi,

i am facing issue as given below scenario.
Current functionality is uploading the data in to custom object by using custom page i.e. 5k records,its working fine.
Requirement is need to upload 10k records,but when i was changed the query limit to 10000,getting below error

"Too many code statements: 200001
Error is in expression '{!readFile}' in component <apex:commandButton> in page svc_bidassetcsvuploadutility

An unexpected error has occurred. Your development organization has been notified."

i belive its throwing the error in insertBIdAssetRecords method but not able to find where do i optmaized the code,so here i am posting my code and i request you to verify it and make any changes if needed.Help is greatly appreciated

VF Page
---------
<apex:page sidebar="false" controller="Svc_BIdAssetCsvUploadUtility" tabStyle="B_SerialNumber__c">
<apex:form >
<apex:sectionHeader title="Upload data Assets"/>
<apex:pagemessages />
<apex:pageBlock >
<apex:pageblocksection columns="1" title="Upload CSV">
<apex:pageBlockSectionItem >
<font color="red"> <b>Please use the standard template to upload Id Asset records. <a href="{!templateUrl}" target="_blank"> Click here </a> to download the template. </b> </font>
<br/> <b>Maximum {!RECORD_PROCESSING_LIMIT} records can be inserted in every load.</b>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:inputFile value="{!fileContentBlob}" filename="{!fileName}" accept="csv" alt="Browse the file to upload"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:commandButton action="{!readFile}" value="Upload" id="theButton" style="width:70px;"/>
</apex:pageBlockSectionItem>
</apex:pageblocksection>
<apex:pageblocksection columns="1" title="Results" rendered="{!NOT(ISNULL(insertedRecords))}">
<apex:pageBlockSectionItem >
<apex:outputText style="font-weight:bold" value="Success: {0} records">
<apex:param value="{!successCount}"/>
</apex:outputText>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText style="font-weight:bold" value="Error: {0} records">
<apex:param value="{!errorCount}"/>
</apex:outputText>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputPanel ><b>For more details download results</b><apex:commandLink action="{!downloadCsv}" value="here" id="theCommandLink"/></apex:outputPanel>
</apex:pageBlockSectionItem>
</apex:pageblocksection>
</apex:pageBlock>
</apex:form>
</apex:page>
---------------------------------------------------
Controller:
/* ==============================================================================
Name : Svc_BIdAssetCsvUploadUtility
Description : Controller class to reads a CSV file and insert Id-Asset records
================================================================================= */
public class Svc_BIdAssetCsvUploadUtility{
private List<ResultWrapper> displayResults;
private String tempalteName = 'BId-Asset Template';
private String templateId;
public transient String fileName{get;set;}
public transient Blob fileContentBlob{get;set;}
public transient Integer errorCount{get;set;}
public transient Integer successCount{get;set;}
public Integer RECORD_PROCESSING_LIMIT{get{return 10000;} private set;}

/*==========CONSTRUCTOR==========*/
public Svc_BIdAssetCsvUploadUtility(){}

/*=============================================================================================
Description : Method to read data from uploaded CSV file and then insert Id-Asset records.
===============================================================================================*/
public Pagereference readFile(){
try{
errorCount = 0;
successCount = 0;
displayResults = new List<ResultWrapper>();

if(fileContentBlob == Null || fileName == Null){
String errorStr = 'Please select a CSV file.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
}
if(!fileName.endsWithIgnoreCase('.csv')){
String errorStr = 'Only CSV files can be processed.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
}

String fileContentStr = fileContentBlob.toString();
List<List<String>> allRecords = parseCSV(fileContentStr,true);

if(allRecords.size() == 0){
String errorStr = 'Uploaded file contains no records.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
} else if(allRecords.size() > RECORD_PROCESSING_LIMIT){
String errorStr = 'You are trying to process ' + allRecords.size() + ' records. Maximum ' + RECORD_PROCESSING_LIMIT + ' records can be processed.';
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,errorStr);
ApexPages.addMessage(errormsg);
return null;
}


Map<String, String> mapAssetPartNameToId = fetchAssetIds(allRecords);
insertBIdAssetRecords(allRecords, mapAssetPartNameToId);

} catch (Exception e) {
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,e.getMessage());
ApexPages.addMessage(errormsg);
}
return null;
}

/*=============================================================================================
Description : Method to insert Id-Asset records.
@params : List<List<String>> allRecords - comma separated values for uploaded records
@params : Map<String, String> mapAssetPartNameToId - Map with Key=>AssetName and Value=> AssetId
@return : void
Modification History:
===============================================================================================*/
private void insertBIdAssetRecords(List<List<String>> allRecords, Map<String, String> mapAssetPartNameToId){
String partAssetName;
displayResults = new List<ResultWrapper>();
List<BId_SerialNumber__c> bId_AssetsToInsert = new List<BId_SerialNumber__c>();

for (Integer count = 0; count < allRecords.size(); count++){
List<String> fieldValues = allRecords.get(count);

ResultWrapper wrapper = new ResultWrapper();
wrapper.serialNumber = fieldValues.get(0).trim();
wrapper.pdtName = fieldValues.get(1).trim();
wrapper.bId = fieldValues.get(2).trim();

B_Id__c tempBId = new B_Id__c();
if(fieldValues.get(2).trim().isNumeric()){
tempBId.B_Id__c = Integer.valueOf(fieldValues.get(2).trim());
} else {
wrapper.notes = 'Id should be a numeric value';
}

BId_SerialNumber__c record = new BId_SerialNumber__c();
record.Asset__c = mapAssetPartNameToId.get(fieldValues.get(0).trim() + ',' + fieldValues.get(1).trim());
record.B_Id__r = tempBId;

bId_AssetsToInsert.add(record);
displayResults.add(wrapper);
}

if(bId_AssetsToInsert.size() > 0){
List<Database.SaveResult> saveResults = Database.insert(bId_AssetsToInsert, false);

Integer index = 0;
for(Database.SaveResult result : saveResults){
if(result.isSuccess()){
displayResults.get(index).bIdAst = result.getId();
displayResults.get(index).status = 'Success';
successCount++;
} else {
//Avoid over writing the custom error messages
if(String.isBlank(displayResults.get(index).notes)){
displayResults.get(index).notes = result.getErrors().get(0).getMessage();
}
displayResults.get(index).status = 'Error';
errorCount++;
}
index++;
}
}
}

/*=============================================================================================
Description : Method to query Asset records based on the Serial Numbers
===============================================================================================*/
private Map<String, String> fetchAssetIds(List<List<String>> allRecords){
Map<String, String> mapAssetPartNameToId = new Map<String, String>();
String baseQryStr = 'SELECT Id,Product2.Name,SerialNumber FROM Asset WHERE SerialNumber IN ';
String whereClause = '';

//Rows with BLANK values should not be included in query
for(List<String> fieldValues : allRecords){
if(String.isNotBlank(whereClause) && String.isNotBlank(fieldValues.get(0).trim())){
whereClause += ',\''+ fieldValues.get(0).trim() + '\'';
} else if(String.isNotBlank(fieldValues.get(0).trim())){
whereClause = '\''+ fieldValues.get(0).trim() + '\'';
}
}

String qryStr = baseQryStr + '(' + whereClause + ')';
List<Asset> listAssets = Database.query(qryStr);
for(Asset ast : listAssets){
mapAssetPartNameToId.put((ast.SerialNumber.trim() + ',' + ast.Product2.Name.trim()), ast.Id);
}

return mapAssetPartNameToId;
}

/*=============================================================================================
Description : Method to download load result in an excel file
===============================================================================================*/
public Pagereference downloadCsv(){
Pagereference pgRef = new Pagereference('/apex/Svc_BIdAssetCsvUploadResults');
pgRef.setRedirect(false);
return pgRef;
}

/*=============================================================================================
Description : Method to create url that points to standard template to load Id-Asset records
===============================================================================================*/
public String getTemplateUrl(){
If(templateId == Null){
List<Document> listDocuments = [Select Id from Document where Name = :tempalteName];

If(listDocuments.size() == 1){
templateId = listDocuments.get(0).Id;
}
}

return URL.getSalesforceBaseUrl().toExternalForm() + '/servlet/servlet.FileDownload?file=' + templateId;
}

/*=============================================================================================
Description : Method to prepare data to download in excel
===============================================================================================*/
public List<List<ResultWrapper>> getInsertedRecords(){
if (displayResults != null && displayResults.size() > 0){
List<List<ResultWrapper>> listResultLists = new List<List<ResultWrapper>>();
List<ResultWrapper> listResults = new List<ResultWrapper>();

ResultWrapper header = new ResultWrapper();
header.serialNumber='<b>Serial Number</b>';
header.pdtName='<b>Product Name</b>';
header.bId='<b>BId</b>';
header.bIdAst='<b>BIdAsset</b>';
header.notes='<b>Notes</b>';
header.status='<b>Status</b>';

listResults.add(header);
Integer count = 1;
for(ResultWrapper result : displayResults){
listResults.add(result);
count++;
if(Count == 1000){ //SFDC limit to display 1000 results on a visualforce page
listResultLists.add(listResults);
listResults = new List<ResultWrapper>();
count = 0;
}
}

if(listResults.size() != 0){
listResultLists.add(listResults);
}
return listResultLists;
}else {
return null;
}
}

=============================================================================================
Description : Method to parse CSV data
Comma separated values of uploaded CSV
===================================================
public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {
List<List<String>> allFields = new List<List<String>>();

// replace instances where a double quote begins a field containing a comma
// in this case you get a double quote followed by a doubled double quote
// do this for beginning and end of a field
contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
// now replace all remaining double quotes - we do this so that we can reconstruct
// fields with commas inside assuming they begin and end with a double quote
contents = contents.replaceAll('""','DBLQT');
// we are not attempting to handle fields with a newline inside of them
// so, split on newline to get the spreadsheet rows
List<String> lines = new List<String>();

lines = contents.split('\n');

Integer num = 0;
for(String line: lines) {
// check for blank CSV lines (only commas)
if (line.replaceAll(',','').trim().length() == 0) continue;

List<String> fields = line.split(',');
List<String> cleanFields = new List<String>();
String compositeField;
Boolean makeCompositeField = false;
for(String field: fields) {
if (field.startsWith('"') && field.endsWith('"')) {
cleanFields.add(field.replaceAll('DBLQT','"'));
} else if (field.startsWith('"')) {
makeCompositeField = true;
compositeField = field;
} else if (field.endsWith('"')) {
compositeField += ',' + field;
cleanFields.add(compositeField.replaceAll('DBLQT','"'));
makeCompositeField = false;
} else if (makeCompositeField) {
compositeField += ',' + field;
} else {
cleanFields.add(field.replaceAll('DBLQT','"'));
}
}

allFields.add(cleanFields);
}
if (skipHeaders) allFields.remove(0);
return allFields;
}

//Wrapper class representing result of inserted records.

public class ResultWrapper{
public String serialNumber{get;set;}
public String pdtName{get;set;}
public String bId{get;set;}
public String bIdAst{get;set;}
public String notes{get;set;}
public String status{get;set;}
}
}
I would look forward to your reply... :)

  • September 26, 2013
  • Like
  • 0

Hi Team,

 

i have 2 custom fileds  i.e startdate and enddate and data type is date/time .so i need a formula as mentioned below scenario

formula is startdate+enddate*8

ex:startdate is friday 9 am and endate is monday 5 pm so if i calculate as per above formula getting 32 hours

but my requirement ,it should not caculate satarday and sunday so the result will be 16 hours

Pls let me know asap.

 

Thanks!

  • December 07, 2012
  • Like
  • 0

hi all

 

in the batch apex sheduler,i did n't provide system.scheduler like data and time,i have mentioned as manually such as follows,

 

batchapexscheduler:

----------------------------

sambatchapexscheduler  testbas=new sambatchapexscheduler();

database.executebatch(testbas,200);

 

so how do i write test class for above and please let me know asap

Thanks!

 

  • October 11, 2012
  • Like
  • 0
HI all, i have scenario like,1 custom object and 2 custom fields i.e. username_c and password__c so i am storing the password in custom object. so what i want is ,whatever storing the password in custom object that wants to be return by using apex class.i was tring to return but i am not getting so pls relsove this issue.but i am not using any vf page. public with sharing class Sample { public static string registerUser() { List obj = new List(); obj = [Select Username__c,Password__c from Login__c where Username__c =:id Limit 1]; return password__c; } THnaks
HI team, i was facing thsi issue in sites,we developed a vf page and when we click the id it will redirect to detaile page and related list.so in related list when i am editing the pericular record its throwing error i.e. unAutherized in the sites.so how do i reslove this issue let me know asap. Thanks!
Hi all, As we know that how trigger execution works but same thing i want to know how apex class execution works i.e. including test classes and when test classes fails.so kindly let me know asap Thanks!

Hi all,

 

It is possible to fetch records from delegated administrators in salesforce .this functionality is possible r not  pls let me know asap.

 

Thanks

  • April 19, 2012
  • Like
  • 0

Hi all,

 

i am fetching records from account by using ajax in salesforce, but i am unable to get it so here i am giving the code so pls make the changes and let me know asap .

 

<apex:page>
<script type="text/javascript">
var __sfdcSessionId = '{!GETSESSIONID()}';
</script>
<script src="/soap/ajax/24.0/connection.js" type="text/javascript">
</script>
<script type="text/javascript">
window.onload= setupPage;

function setupPage()
{
var result = sforce.connection.query("select name, id from account where limit:=1");
var queryMore = true;
var output = "";
while (queryMore) {
var records = result.getArray("records");
for (var i = 0; i < records.length; i++) {
var account = records[i];

output += account.Id + " " + account.Name + "<br>";
}
if (result.getBoolean("done")) {
queryMore = false;
} else {
result = sforce.connection.queryMore(result.queryLocator);
}
}
}
</script>
<div id="output"> </div>
</apex:page>

 

Thanks

  • April 18, 2012
  • Like
  • 0

Hi,

 

i just want to understand writing the test classes using assert equals and assert.so kindly give me the small example in vf.

 

 

Thanks

  • April 03, 2012
  • Like
  • 0