• Varun Chopra
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 19
    Questions
  • 1
    Replies
Hi,

I am creating document in salesforce under "My personal Folders" or in any other folder i'e created througn managed package. When I am trying to open that document from "Document dettail page" by clicking on view document link, it is saying insufficient preveliges.

I am logged in as system admin also I have checked the permissions for document and folder in system admin profile. I have all the permissions to edit delete or view file. But still I am not able to see the filecontent. 

Is there any other palce where permissions are defined?

Please help!
Hi 

I am facing a wired issue in my clients org. There are two fields in the clients org with same label suppose ABC. 

One from our package (xyz )and one in their own org.  Our code is executing dynamic query using salesforce  
Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap()  method.
 
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
    
 string fieldnames=' ';
 for(String s : objectFields.keySet()) 
 {
   s = objectFields.get(s).getDescribe().getName(); 
   fieldnames+=s+','; 
 }
        fieldnames=fieldnames.substring(0,fieldnames.length()-1);   
string query=  'SELECT '+fieldnames +' from xyz_sfObj__c';
List <xyz_sfObj__c> sfObjData = Database.query(query);

//return fieldnames;

When the above query is executing salesforce is throwing the following error:

Duplicate Field Selected: xyz_ABC__c

For now I hvae fixed it by renaming the field label but is there anything that we can do in our code to fix this issue ?

Thanks In Advance !
Hi 

I am facing a wired issue in my clients org. There are two fields in the clients org with same label suppose ABC. 

One from our package (xyz )and one in their own org.  Our code is executing dynamic query using salesforce  
Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap()  method.
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
    
 string fieldnames=' ';
 for(String s : objectFields.keySet()) 
 {
   s = objectFields.get(s).getDescribe().getName(); 
   fieldnames+=s+','; 
 }
        fieldnames=fieldnames.substring(0,fieldnames.length()-1);   
string query=  'SELECT '+fieldnames +' from xyz_sfObj__c';
List <xyz_sfObj__c> sfObjData = Database.query(query);

//return fieldnames;



When the above query is executing salesforce is throwing the following error:

Duplicate Field Selected: xyz_ABC__c

For now I hvae fixed it by renaming the field label but is there anything that we can do in our code to fix this issue ?

Thanks In Advance !
Hi

I am upserting records using curl php in salesfroce using following code:
$url = https://na1.salesforce.com/…/Acco…/customExtIdField__c/11999

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestType);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Length: ' . strlen($content), 'Content-Type: application/json','Authorization: OAuth '.$atoken));
It was working fine , until I was using normal external Id, Today I have modified my external Id and set it as unique in salesforce and now my code is throwing this error.

[message] => duplicate value found: customExtIdField__c duplicates value on record with id: 001d0000003ja0H [errorCode] => DUPLICATE_VALUE [fields] => Array ( )
Please help , Thanks In Advance !
I am trying to upload a csv file in salesforce through apex code. In salesforce after uploading the csv file , date field is showing one day off.

For e.g. I am uploading 16-08-2015 in date field but in salesforce it shows 15-08-2015.

I know it is due to timezone problem but i want to resolve it. Can anyone have any idea to resolve this??

Thanks in advance!!!!
Hi

I am facing two very weired issues.

1. I have created a triiger on task (before insert, before update) event.
In which I am assigning who Id to task on the basis of what Id. Code is working fine in the dev org. But the issue is when when I am doploying package in subscriber orgs, it is working in some orgs, bt not for all.
I can see Who Id value in the developer org in the (after insert, after update ) task, but In the salesforce UI who Id is not linked to the task.

2.  In case of before update of task trigger I am storing task Id's in a set .  The same issue like above I am facing here. i.e. for some orgs it is working perfectly fine while others a blank set is created in the develpoer console.

Please help.
Thanks In advance !!!
Hi All,
I have created a global class even all its methods and variables are global. Now I have to access methods of that global class(which is managed as i have uploaded it through package). But it is giving 
Error: Compile Error: Invalid type: ClanName
Please Help.
Hi,

I have a button 'View form'. When I click on this button then a php page will appear and check if file is ready to show or not. If file is ready then it show to user else i have to show a message then File is not ready yet. You have to try after some time. How can i do that. 
Hi

I tried to create a webservice using apex in salesforce. But when I am trying to access it from another class it is throwing following error.

[{"errorCode":"NOT_FOUND","message":"Could not find a match for URL /FieldCase"}]

My Webservice Code:
 
@RestResource(urlMapping='/FieldCase')
global with sharing class RESTCaseController {

@HttpGet   
  global static List<Account> createNewCase() {
       List<Account> company = [Select ID, Name, BillingState from Account where Name = 'AproposeInc'];
        return company;
  }
}

Class code in which I am accessing the the webservice
public with sharing class CallRestCaseController {
    
     public Pagereference callAPI()
    {
         ValidaCredenciais('reee ','eeee', null);
         return null;
    }
    
    
    public String ValidaCredenciais(String Usuario, String Senha, String SessionId) {
        try
        { 
       
            HttpRequest req = new HttpRequest();         
            Http http = new Http();         
            req.setMethod('GET');         
            req.setEndpoint('https://salesfoce.instance.name/services/apexrest/FieldCase');         
           // req.setBody('{"usuario": "' + Usuario + '", "senha": "' + Senha + '", "orgId": "' + System.Userinfo.getOrganizationId() + '"}');
            req.setHeader('Content-Type', 'application/json');
            req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
          //  req.setBody('{"companyName":"AproposeInc"}');
            HTTPResponse resp = http.send(req);
            String RetornoValida = resp.getBody();    
           
            system.debug('comingg ============= ???? '+RetornoValida);
            return RetornoValida;
         }
        catch(System.CalloutException e)
        {
        System.debug('Sorry, You have an error ' + e.getMessage());
        }
        return null;
     }

}

I have also added the salesforce instance name in remote sites. But still no success. I am accessing it in the same org.
Please help.

Also I have to access it for another org, then what should I do ??

Thanks in advance !
 
Hi

I have created  a visual force flow and I need to attach a file within the flow.
I know it is only possible by embedding the flow in the visual force page. But the thing is the attach file option is displaying in each screen of the flow. So If i attach file in the very first screen (When record is not creted yet from flow), then it will throw the parent Id missing error.

Is there any way to show File attachment option only at a perticular screen where we know record Id is not null.

Visual force Page code :
 
<apex:page controller="AttachFileInFlow"  >
 <flow:interview name="NewclientScreen1"  interview="{!myflow}">

</flow:interview>

<apex:form >

<apex:outputText value="Input File: "/><apex:inputFile value="{!attach.body}" filename="{!attach.name}"/><br/>
<apex:commandButton value="Upload" action="{!upload}"/>
</apex:form>

</apex:page>
Apex Class Code
 
public with sharing class AttachFileInFlow  {
 public String parentId {get;set;}
 public Attachment attach {get;set;}
 public String objectID {get;set;} 
 public Flow.Interview.NewclientScreen1 myflow{get;set;}
 


  public String getObjectID()
{

     if (myflow == null) { 
            system.debug('myflow.Insurance_Quote_Id ==== ??' + null );
            return null; 
      }
      else {
             objectID =myflow.Insurance_Quote_Id ;//myflow.objectId;
             system.debug('myflow.Insurance_Quote_Id ==== ??' +  objectID);
             return objectID;
     }
}
     
       public AttachFileInFlow(){
                attach = new Attachment();
                objectID = getObjectID();
        }
   
     public ApexPages.Pagereference upload(){
      
            if(myflow != null)
           {
                   system.debug('myflow.objectID ==== ??' +   objectID);
                   system.debug('myflow.objectID ==== ??' +   myflow.Insurance_Quote_Id);
                   Attachment a = attach.clone(false, true, false, false);
                   a.ParentId = myflow.Insurance_Quote_Id;
                   
                   attach.Body = null;
                    insert a;
             
              }
              return null;
          
     }
}

Please Help !

Thanks In Advance,


 
Hi

I am inserting record using code in salesforce while I get the following error.

Upsert failed. First exception on row 1; first error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: this ID value isn't valid for the user: 012G0000001FTwqIAG: [RecordTypeId]

I know this error come when user does't have permissions foe that perticular ID. But I checked the recordtype setting for this  UserProfile and RecordTypeId is added for this UserProfile.

Is there anything that I am missing ?
Please Help .

Thanks in advance !
Hi
I did some changes in my class, which is scheduled in different org's. After packaging when I tired to upgrage package in ogr's, it failed in some of the org's.
Error is :
Unexpected Failure
An unexpected failure was experienced during the upgrade. The subscriber's organization was unaffected. Contact salesforce.com Support through your normal channels and provide the following error number: 892298956-449953 (-195865981).

 
Hi

I am upserting two records using code having same external Id. According to me it should insert first record and update second record with first one. But code is creating two records with same external Id. Can anyone explain why ?

Also please help me to resolve this issue.

 
Hi I am triying to run ajax on my visualforce page. But I am getting ready state= 0.
In chrome I was getting following error.

No 'Access-Control-Allow-Origin' header is present on the requested resource.


Here is my code
$.ajax({
            type:"GET",
            url:'https://www.foragentsonly.com/',
            dataType:"html",
            beforeSend: function(xhr) {
               xhr.setRequestHeader('X-User-Agent', 'MyClient');
            },
            success:function(data) {
                alert(data);
              
            },
            error:function(errorStatus,xhr) {
                alert("Error"+JSON.stringify(errorStatus));
            }
        });
  // document.getElementById('theIframe').src = url;

}

 

Hi

I have added an Iframe in my visual force page. For some sites it is redirecting to the Url itself. This is due to the code used in the wesite to prevent frame brusting.

I tried to use Sandbox=" " property of html5 but it doesn't work.

I also used following javascrippt code.

window.onbeforeunload = function (evt) {    

      return "This will end your session";
}



This image is not available because: You don’t have the privileges to see it, or it has been removed from the system

But it shows an popup box with two buttons stay on page and leave page every time my page refresh. Is there any way to stop this redirection without showing this popup.
Hi

I have added a visual force page in the custom object layout.
After packaging when I updated latest package in the org, visual force page is not added in the layout.
While visual force page is added in the package.

Please help to resove this issue.

Thanks !
Hi,

I am stuck with an problem with my schedular. I am tyring to read files from S3 bucket using amazon S3 api calls. When I am trying to call this method using schedular it gives me error :
  System.CalloutException: Callout from scheduled Apex not supported.

Here is my schedula class :

global class ScheduleXMLDownload implements Schedulable{
  
   global void execute(SchedulableContext SC) {
        downloadFiles();
    }
  
      public static void downloadFiles(){
       try{
          ReadXml.requestIvans();
         }
   catch (DmlException ex)  { 
          system.debug('error insert DefaultProducer '); 
  
         
        }
    }
   
}


Here is my method I am calling in shedular.


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

@future(callout=true)
     public static void requestIvans(){
        Http h = new Http();
        AmazonAccess amz = new AmazonAccess();
        
        CanaryAMS__Defaults__c property = CanaryAMS__Defaults__c.getValues('MailBoxId');
        String mailBoxId = property.CanaryAMS__value__c;
       
        Map< String,String> xmlFileList = new map<String,String>();
        
        String aWSAccessKeyId = amz.key;
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        SaveObjects.ListEntry[] bucketList  = amz.listBucket('canary.ams.xml',mailBoxId);
       
        List<String> xmlResponseList = new List<String>();
        List<String> bucketKeys = new List<String>();
        String filesToDelete = ''; 
        boolean runSchedular = true;
        Integer countRun = 0 ;
        do {
  
       if(bucketList!=null && !bucketList.isEmpty()){
        runSchedular = false;
        Integer maxFiles  = bucketList.size();
        if(maxFiles>3){
        maxFiles = 3;
        }
           for(integer i=1; i<maxFiles; i++){
               Datetime now = DateTime.now();
               Datetime expireson = now.AddSeconds(30+i);
               Long Lexpires = expireson.getTime()/1000;
               Lexpires = Lexpires + i;
               bucketToList = 'canary.ams.xml';
               String stringtosign = 'GET\n\n\n'+Lexpires+'\n/'+bucketToList+'/'+bucketList[i].Key;
          
               String signed = amz.make_sig(stringtosign);
              
               String url = 'http://'+bucketToList+'.s3.amazonaws.com/'+bucketList[i].Key+'?AWSAccessKeyId='+aWSAccessKeyId+'&Expires='+Lexpires+'&Signature='+signed;
        //     system.debug('shalini ======= > '+url);
          //     String url =  'https://s3-us-west-2.amazonaws.com/canary.ams.xml/'+bucketList[i].Key;
               bucketKeys.add(bucketList[i].Key);
               system.debug(url);
               //String url = EncodingUtil.URLENCODE(url1,'UTF-8');
               req.setEndPoint(url);
               req.setMethod('GET');
               res = h.send(req);
             
               String response = res.getBody();
               ReadXml readXml = new ReadXml();
               if(readXml.checkXMlFormat(response)){
                //filesToDelete = filesToDelete+bucketList[i].Key+',';
                xmlResponseList.add(response);
                xmlFileList.put(bucketList[i].Key,response);
               }
            
          }
          ReadXml readXml = new ReadXml();
          readXml.processXMl(xmlFileList);
          
         /* String url =  'http://ec2-54-186-194-3.us-west-2.compute.amazonaws.com/Script/UploadToS3Bucket/moveToArchiveFolder.php?key=';
          url = url+filesToDelete;
          req.setEndPoint(url);
          req.setMethod('GET');
          res = h.send(req);
         
         
          String response = res.getBody();
          for(String resp : xmlResponseList){
              if(checkXMlFormat(resp)){
                parse(resp);
              }
          } */
         
         
      }else{
      system.debug(' ==================== schedular Error ====================');
           if(countRun < 3 )  
           {   
    countRun ++ ;
    runSchedular = true;
    system.debug('S3 bucket is not accessible '+Apexpages.Severity.ERROR ) ;
           }
           else
           {
     runSchedular = false;
           }
      }
      } while (runSchedular);
       
       
    }


   
   I have searched on google and most of solutions are to add @future annotaion over my method. I have tried this, but it is still not working.
   Please let me know whats wrong with my code?

Thanks
Hi I am crating a visualforce page showing some data with one lookup field. Page is loading in my developer account (having 100 records).  Even I have used te paginaion i.e. showing only 20 records per page. After creating package when I am installing package in my live accoun t(having 2000+  records) and trying to open that page but  it is giving the following error.
Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 604.391KB

I tried to check the view state in my developer account. Only 6.44 kb is used.  While live account does'nt showing the view state I dont know why ?
Please check my class and visual force page code below :

Class Code
public with sharing class PolicyWrapperClassController {
public List<wPolicy> policyList {get; set;}

//public String accountName {get; set;}
//public Id accountId {get; set;}

   private integer totalRecs = 0;
private integer OffsetSize = 0;
private integer LimitSize= 20;

public PolicyWrapperClassController()
{
totalRecs = [select count() from CanaryAMS__Policy__c where CanaryAMS__To_be_Reviewed__c = true];
}
  
    public List<wPolicy> getPolicies() {
        if(policyList == null) {
             policyList = new List<wPolicy>();
           
             Map<Id, Contact> ContactsDetail = new Map<Id, Contact>();
             List<Contact> contacts = [ SELECT Id,Name from Contact];
          
              for(Contact c : contacts){
                  ContactsDetail.put(c.id, c);
              }
            
                Map< Id,String> recordTypeMap = RecordTypeMap();
                 List<CanaryAMS__Policy__c> oldpoliciesList = new List<CanaryAMS__Policy__c>();
            oldpoliciesList = [SELECT Id,CanaryAMS__Effective_Date__c,Name,CanaryAMS__Policy_Number__c,CanaryAMS__Carrier__r.Name,CanaryAMS__PolicyTypeCd__c,CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c,CanaryAMS__Carrier_Product__c from CanaryAMS__Policy__c where  CanaryAMS__To_be_Reviewed__c = false];  
             //system.debug('SELECT Id,Name,CanaryAMS__Policy_Number__c,CanaryAMS__Effective_Date__c,CanaryAMS__Carrier__r.Name,CanaryAMS__PolicyTypeCd__c,CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c,CanaryAMS__Carrier_Product__c from CanaryAMS__Policy__c where  CanaryAMS__To_be_Reviewed__c = true LIMIT'  LIMIT :LimitSize OFFSET :OffsetSize  +LimitSize+ 'OFFSET' +OffsetSize);
             for(CanaryAMS__Policy__c p: Database.Query('SELECT Id,Name,RecordTypeId,CanaryAMS__Policy_Number__c,CanaryAMS__Effective_Date__c,CanaryAMS__Carrier__r.Name,CanaryAMS__PolicyTypeCd__c,CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c,CanaryAMS__Carrier_Product__c from CanaryAMS__Policy__c where CanaryAMS__To_be_Reviewed__c = true LIMIT :LimitSize OFFSET :OffsetSize')) {
                // As each contact is processed we create a new wPolicy object and add it to the policyList
                //system.debug('test=========>>>>' + p);
                  wPolicy policyWrapper = new wPolicy(p);
                
               policyWrapper =  fetchSuggestedPolicies(p,oldpoliciesList,ContactsDetail,policyWrapper);
                  
                  if(policyWrapper.bestMatch != null)
                  {
                   policyWrapper.policyId = policyWrapper.bestMatch.Id;
                   policyWrapper.policyName = policyWrapper.bestMatch.CanaryAMS__Policy_Number__c;
                  }
           /*       
                  try {
                   Contact contact = ContactsDetail.get(p.CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c);     
                   policyWrapper.con = contact;
                  }catch(DmlException e) {
               system.debug('info putinto ivansreulsts. test>>>'+p.Name);
            } catch(Exception e) {
                system.debug('info putinto ivansreulsts. test6>>>'+p.Name);
            }
            */
            try {
                   String name = recordTypeMap.get(p.RecordTypeId);     
                   policyWrapper.recordTypeName = name;
                   //policyWrapper.recordTypeId = p.RecordTypeId;
                  }catch(DmlException e) {
            } catch(Exception e) {
            }
           
                
                
                 policyList.add(policyWrapper);
            }
        }
        return policyList;
    }


    public PageReference processSelected() {
     system.debug('coming -----');
                //We create a new list of Contacts that we be populated only with Contacts if they are selected
        List<wPolicy> selectedPolicies = new List<wPolicy>();
        for(wPolicy wPol: getPolicies()) {
            if(wPol.selected == true) {
             system.debug(wPol);
                selectedPolicies.add(wPol);
            }
          
         }
         system.debug('selectedPolicies -----'+selectedPolicies);
  
  if(!selectedPolicies.isEmpty())
        {
         fetchData(selectedPolicies);
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.CONFIRM, 'Policy successfully merged'));
     }
        else
        {
           ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, 'Select atleast one Policy you want to merge'));
        }
 
        // Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
       /* System.debug('These are the selected Contacts...');
        for(CanaryAMS__Policy__c pol: selectedPolicies) {
            system.debug('selectedPolicies -----'+pol);
        }*/
        policyList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
        return null;
    }
    

      public PageReference markAsResolved() {
       system.debug('coming here -----');
                //We create a new list of Contacts that we be populated only with Contacts if they are selected
        List<wPolicy> selectedPolicies = new List<wPolicy>();
// system.debug('resolve these policies -----'+getPolicies);
        //We will cycle through our list of wPolicys and will check to see if the selected property is set to true, if it is we add the Contact to the selectedPolicies list
        for(wPolicy wPol: getPolicies()) {
          //  system.debug('resolve these policies -----'+wPol);
            if(wPol.selected == true) {
            system.debug(wPol);
            
             //getData(oldPolicyId, newPolicyId);
             //system.debug(wPol.pol.CanaryAMS__Account__r.Primary_Contact__c);
           
                selectedPolicies.add(wPol);
            }
          
         }
          
   system.debug('selectedPolicies -----'+selectedPolicies);
    if(!selectedPolicies.isEmpty())
         {
          resolveSelectedPolicies(selectedPolicies);
       //ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.CONFIRM, 'Policy successfully merged'));
      }
         else
         {
            //ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, 'Select atleast one Policy you want to merge'));
         }
   policyList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
        return null;
    }


    // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
    public class wPolicy {
        public CanaryAMS__Policy__c pol {get; set;}
        public Boolean selected {get; set;}
       // public Contact con {get; set;}
        public Map<CanaryAMS__Policy__c, Integer> suggestedPolicies {get; set;}
        public CanaryAMS__Policy__c bestMatch {get; set;}
       
        //public CanaryAMS__Policy__c suggestedPol {get; set;}
      //  public String policyName {get; set;}
       // public String recordTypeId {get; set;}
        public String recordTypeName {get; set;}
        public String policyId {get; set;}
        public String policyName {get; set;}
     
        //This is the contructor method. When we create a new wPolicy object we pass a Contact that is set to the con property. We also set the selected value to false
        public wPolicy(CanaryAMS__Policy__c p) {
            pol = p;
            selected = false;
        }
    }
   
   
   public String fetchFields(String objectName)
    {
    
  Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();

  string fieldnames=' ';
  for(String s : objectFields.keySet())
  {
   s = objectFields.get(s).getDescribe().getName() ;
      fieldnames+=s+',';
  }
     fieldnames=fieldnames.substring(0,fieldnames.length()-1);
     return fieldnames;
    
    }
   
    public void fetchData(List<wPolicy> selectedPolicies)
     { 
      System.debug('selectedPolicies3456...'+selectedPolicies);
     
       List<CanaryAMS__Policy__c> policiesToUpdate =  new List<CanaryAMS__Policy__c>();
       List<CanaryAMS__Policy__c> policiesToUpsert =  new List<CanaryAMS__Policy__c>();
       List<CanaryAMS__Policy_Contact_Junction__c> updateInsuredData = new List<CanaryAMS__Policy_Contact_Junction__c>();
       List<CanaryAMS__Vehicle__c> updateVehicleData = new List<CanaryAMS__Vehicle__c>();
       List<CanaryAMS__Claim__c> updateClaimData = new List<CanaryAMS__Claim__c>();
       List<CanaryAMS__Additional_Interests__c> updateAdditionalInterstData = new List<CanaryAMS__Additional_Interests__c>();
       List<CanaryAMS__Form__c> updateFormData = new List<CanaryAMS__Form__c>();
       List<CanaryAMS__Coverage__c> updateCoverageData = new List<CanaryAMS__Coverage__c>();
      
       string fieldnames =  fetchFields('CanaryAMS__Policy__c');
       string query=  'SELECT '+fieldnames +' from CanaryAMS__Policy__c';
           List <CanaryAMS__Policy__c> policiesData = Database.query(query);
           Map<Id, CanaryAMS__Policy__c> policiesMap = new Map<Id, CanaryAMS__Policy__c>();
          for(CanaryAMS__Policy__c pol : policiesData){
              policiesMap.put(pol.Id, pol);
          }
     
       List<CanaryAMS__Vehicle__c> vehicleData =  [select id ,Name, CanaryAMS__Policy__c from CanaryAMS__Vehicle__c];
      List<CanaryAMS__Claim__c> claimData = [select id ,Name, CanaryAMS__Policy__c from CanaryAMS__Claim__c ];
   List<CanaryAMS__Coverage__c> coverageData = [select id ,Name, CanaryAMS__Policy__c from CanaryAMS__Coverage__c];
   List<CanaryAMS__Additional_Interests__c> additionalInterstData = [select id ,Name, CanaryAMS__Policy__c from CanaryAMS__Additional_Interests__c];
   List<CanaryAMS__Form__c> formData  = [select id ,Name, CanaryAMS__Policy__c from CanaryAMS__Form__c ];
   List<CanaryAMS__Policy_Contact_Junction__c> insuredData =  [select id ,Name, CanaryAMS__Policy__c ,CanaryAMS__Contact__c from CanaryAMS__Policy_Contact_Junction__c ];
  
       Map<String, List<CanaryAMS__Vehicle__c>> polVehicleMap = new Map<String, List<CanaryAMS__Vehicle__c>>();     
         Map<String, List<CanaryAMS__Claim__c>> polClaimMap = new Map<String, List<CanaryAMS__Claim__c>>();
         Map<String, List<CanaryAMS__Coverage__c>> polCoverageMap = new Map<String, List<CanaryAMS__Coverage__c>>();
         Map<String, List<CanaryAMS__Additional_Interests__c>> polAddIntMap = new Map<String, List<CanaryAMS__Additional_Interests__c>>();  
         Map<String, List<CanaryAMS__Form__c>> polFormMap = new Map<String, List<CanaryAMS__Form__c>>(); 
         Map<String, List<CanaryAMS__Policy_Contact_Junction__c>> polConJunctionMap = new Map<String, List<CanaryAMS__Policy_Contact_Junction__c>>(); 
     
      if(!insuredData.isEmpty())
      {
        for(CanaryAMS__Policy_Contact_Junction__c insured : insuredData){
                String policyId = insured.CanaryAMS__Policy__c;
                List <CanaryAMS__Policy_Contact_Junction__c> polConJunctionList = polConJunctionMap.get(policyId);
                 if(polConJunctionList == null )
                 {
                   polConJunctionList =  new List<CanaryAMS__Policy_Contact_Junction__c>();
                 }
                 polConJunctionList.add(insured);
                 polConJunctionMap.put(policyId, polConJunctionList);
        }
      }
     
      if(!formData.isEmpty())
      {
        for(CanaryAMS__Form__c form : formData){
                String policyId = form.CanaryAMS__Policy__c;
                List <CanaryAMS__Form__c> polFormList = polFormMap.get(policyId);
                 if(polFormList == null )
                 {
                   polFormList =  new List<CanaryAMS__Form__c>();
                 }
                 polFormList.add(form);
                 polFormMap.put(policyId, polFormList);
        }
      }
     
      if(!additionalInterstData.isEmpty())
      {
        for(CanaryAMS__Additional_Interests__c AI : additionalInterstData){
                String policyId = AI.CanaryAMS__Policy__c;
                List <CanaryAMS__Additional_Interests__c> polAddIntList = polAddIntMap.get(policyId);
                 if(polAddIntList == null )
                 {
                   polAddIntList =  new List<CanaryAMS__Additional_Interests__c>();
                 }
                 polAddIntList.add(AI);
                 polAddIntMap.put(policyId, polAddIntList);
        }
      }
     
     
      if(!coverageData.isEmpty())
      {
        for(CanaryAMS__Coverage__c cov : coverageData){
                String policyId = cov.CanaryAMS__Policy__c;
                List <CanaryAMS__Coverage__c> polCoverageList = polCoverageMap.get(policyId);
                 if(polCoverageList == null )
                 {
                   polCoverageList =  new List<CanaryAMS__Coverage__c>();
                 }
                 polCoverageList.add(cov);
                 polCoverageMap.put(policyId, polCoverageList);
        }
      }
      
      if(!claimData.isEmpty())
      {
        for(CanaryAMS__Claim__c claim : claimData){
                String policyId = claim.CanaryAMS__Policy__c;
                List <CanaryAMS__Claim__c> polClaimList = polClaimMap.get(policyId);
                 if(polClaimList == null )
                 {
                   polClaimList =  new List<CanaryAMS__Claim__c>();
                 }
                 polClaimList.add(claim);
                 polClaimMap.put(policyId, polClaimList);
        }
      }
     
      if(!vehicleData.isEmpty())
      {
        for(CanaryAMS__Vehicle__c veh : vehicleData){
                String policyId = veh.CanaryAMS__Policy__c;
                List <CanaryAMS__Vehicle__c> polVehicleList = polVehicleMap.get(policyId);
                 if(polVehicleList == null )
                 {
                   polVehicleList =  new List<CanaryAMS__Vehicle__c>();
                 }
                 polVehicleList.add(veh);
                 polVehicleMap.put(policyId, polVehicleList);
        }
      }
        Map<Id,String> policyIdsMap = new Map<Id,String>();
      
      for(wPolicy wPols: selectedPolicies) {
               
          //Id oldPolicyId1 = wPols.policyId;
           String oldPolicyId = wPols.policyId;
              // system.debug(newPolicyId);   
       if(oldPolicyId != null && !oldPolicyId.equals('') )
       {
               
       CanaryAMS__Policy__c Policy = new CanaryAMS__Policy__c();
     
         //String oldPolicyId = wPols.policyId;
             Id newPolicyId = wPols.Pol.Id ;
         // Id newPolicyId = wPols.Pol.Id ;
            
             policyIdsMap.put(newPolicyId,oldPolicyId);
       CanaryAMS__Policy__c newPolicyData = policiesMap.get(newPolicyId);   //Database.query(query);;
          CanaryAMS__Policy__c oldPolicyData = policiesMap.get(oldPolicyId);  //[SELECT Id,Name,CanaryAMS__Policy_Number__c from CanaryAMS__Policy__c where Id = : oldPolicyId];
       System.debug('oldPolicyData ==== '+oldPolicyData);
       //CanaryAMS__Policy__c policyUpdate = new CanaryAMS__Policy__c();
       Policy.Id = newPolicyData.Id;
          Policy.CanaryAMS__Policy_Number__c = newPolicyData.CanaryAMS__Policy_Number__c+'_DELETE';
          Policy.CanaryAMS__To_be_Reviewed__c = false ;
       Policy.Name = newPolicyData.Name+'_DELETE';
       Policy.CanaryAMS__Policy_Number_Ex__c = Policy.CanaryAMS__Policy_Number__c;
       policiesToUpdate.add(Policy);
         
       
       
        newPolicyData.Id = oldPolicyData.Id;
           newPolicyData.CanaryAMS__To_be_Reviewed__c = false ;
          //  newPolicyData.CanaryAMS__To_be_Reviewed__c = false ;
           policiesToUpsert.add(newPolicyData);
          
          List<CanaryAMS__Vehicle__c> polVehicleList =   polVehicleMap.get(newPolicyId);
       System.debug('polVehicleList ==== '+polVehicleList);
              if(polVehicleList != null && !polVehicleList.isEmpty())
        { 
            for(CanaryAMS__Vehicle__c Vehicle : polVehicleList )
         {
            CanaryAMS__Vehicle__c updateVehicle = new CanaryAMS__Vehicle__c();
          updateVehicle.CanaryAMS__Policy__c =  oldPolicyId;
          updateVehicle.Id = Vehicle.Id;
          updateVehicleData.add(updateVehicle);
         }
        }
        
          List<CanaryAMS__Coverage__c> polCoverageList =   polCoverageMap.get(newPolicyId);
       System.debug('polCoverageList ==== '+polCoverageList);
          if(polCoverageList != null && !polCoverageList.isEmpty())
        { 
            for(CanaryAMS__Coverage__c Coverage : polCoverageList )
         {
            CanaryAMS__Coverage__c updateCoverage = new CanaryAMS__Coverage__c();
          updateCoverage.CanaryAMS__Policy__c = oldPolicyId;
          updateCoverage.Id = Coverage.Id;
          updateCoverageData.add(updateCoverage);
         }
        }
       
        List<CanaryAMS__Claim__c> polClaimList =   polClaimMap.get(newPolicyId);
       System.debug('polClaimList ==== '+polClaimList);
       
        if(polClaimList != null && !polClaimList.isEmpty())
        { 
            for(CanaryAMS__Claim__c Claim : polClaimList )
         {
            CanaryAMS__Claim__c updateClaim = new CanaryAMS__Claim__c();
          updateClaim.CanaryAMS__Policy__c = oldPolicyId;
          updateClaim.Id = Claim.Id;
          updateClaimData.add(updateClaim);
         }
        }
       
        List<CanaryAMS__Additional_Interests__c> polAddIntList =   polAddIntMap.get(newPolicyId);
       System.debug('polAddIntList ==== '+polAddIntList);
       
        if(polAddIntList != null && !polAddIntList.isEmpty())
        { 
            for(CanaryAMS__Additional_Interests__c AdditionalInterst : polAddIntList )
         {
            CanaryAMS__Additional_Interests__c updateAdditionalInterst = new CanaryAMS__Additional_Interests__c();
          updateAdditionalInterst.CanaryAMS__Policy__c = oldPolicyId;
          updateAdditionalInterst.Id = AdditionalInterst.Id;
          updateAdditionalInterstData.add(updateAdditionalInterst);
         }
        }
       
        List<CanaryAMS__Form__c> polFormList =   polFormMap.get(newPolicyId);
       System.debug('polFormList ==== '+polFormList);
        if(polFormList != null && !polFormList.isEmpty())
        { 
            for(CanaryAMS__Form__c Form : polFormList )
         {
            CanaryAMS__Form__c updateForm = new CanaryAMS__Form__c();
          updateForm.CanaryAMS__Policy__c =oldPolicyId;
          updateForm.Id = Form.Id;
          updateFormData.add(updateForm);
         }
        }
       
        List<CanaryAMS__Policy_Contact_Junction__c> polConJunctionList =   polConJunctionMap.get(newPolicyId);
       System.debug('polConJunctionList ==== '+polConJunctionList);
       
        if(polConJunctionList != null && !polConJunctionList.isEmpty())
        { 
            for(CanaryAMS__Policy_Contact_Junction__c Insured : polConJunctionList )
         {
            CanaryAMS__Policy_Contact_Junction__c insuredForm = new CanaryAMS__Policy_Contact_Junction__c();
          insuredForm.CanaryAMS__Policy__c =oldPolicyId;
          insuredForm.Id = Insured.Id;
          insuredForm.CanaryAMS__Composite_Key__c = ''+insuredForm.CanaryAMS__Contact__c+insuredForm.CanaryAMS__Policy__c;
          updateInsuredData.add(insuredForm);
         }
        }
           }
      }
    
     if(!updateVehicleData.isEmpty())
      {
      update updateVehicleData;
      System.debug('updateVehicleData ==== '+updateVehicleData);
      }
      if(!updateClaimData.isEmpty())
      {
      update updateClaimData;
      System.debug('updateClaimData ==== '+updateClaimData);
      }
     if(!updateCoverageData.isEmpty())
      {
      update updateCoverageData;
      System.debug('updateCoverageData ==== '+updateCoverageData);
      }
       if(!updateAdditionalInterstData.isEmpty())
      {
      update updateAdditionalInterstData;
      System.debug('updateAdditionalInterstData ==== '+updateAdditionalInterstData);
      }
      if(!updateFormData.isEmpty())
      {
      update updateFormData;
      System.debug('updateFormData ==== '+updateFormData);
      }
      if(!updateInsuredData.isEmpty())
      {
      update updateInsuredData;
      System.debug('updateInsuredData ==== '+updateInsuredData);
      }
      if(!policiesToUpdate.isEmpty())
      {
      delete policiesToUpdate ;
      System.debug('policiesToUpdate ==== '+policiesToUpdate);
      }//CanaryAMS__Policy_Number_Ex__c;
     
      if(!policiesToUpsert.isEmpty())
      {
      upsert policiesToUpsert;
      System.debug('policiesToUpsert ==== '+policiesToUpsert);
      }
  
   
    }
   
   
    public wPolicy fetchSuggestedPolicies(CanaryAMS__Policy__c newPolicy,List<CanaryAMS__Policy__c> oldPolicies,Map<Id, Contact> ContactsDetail, wPolicy policyWrapper)
    {
   Map<CanaryAMS__Policy__c, Integer> suggestedPolicies = new Map<CanaryAMS__Policy__c, Integer>();
      CanaryAMS__Policy__c bestMatch ;
      Integer MaxCount = 0;
     
      for(CanaryAMS__Policy__c pol : oldPolicies)
      { 
       Integer value = 0;
     
       if(newPolicy.CanaryAMS__Carrier_Product__c ==  pol.CanaryAMS__Carrier_Product__c)
       {
        value = value + 1;
         }
      
       if(newPolicy.CanaryAMS__Effective_Date__c ==  pol.CanaryAMS__Effective_Date__c)
       {
        value = value + 1;
       }
      
       Contact oldContact ;
       Contact newContact;
      
       oldContact = ContactsDetail.get(pol.CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c);
       newContact= ContactsDetail.get(newPolicy.CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c);
      
       if(oldContact != null && newContact !=null)
       {
        String oldPolicyContactName= ContactsDetail.get(pol.CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c).Name;
        String newPolicyContactName= ContactsDetail.get(newPolicy.CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c).Name;
        ContactsDetail.get(pol.CanaryAMS__Account__r.CanaryAMS__Primary_Contact__c);
      
        if(oldPolicyContactName!= null && oldPolicyContactName.equals(newPolicyContactName) )
        {
         value = value + 1;
        }
       }
      
       if(value > 0)
        {
         suggestedPolicies.put(pol,value);
      
        if(value >= MaxCount)  
        {
         bestMatch =  pol;
        }
        }
      }
     
      policyWrapper.suggestedPolicies = suggestedPolicies;
      policyWrapper.bestMatch = bestMatch;
    
      return policyWrapper;
     
    }
   
    public void resolveSelectedPolicies(List<wPolicy> selectedPolicies)
    {
      List<CanaryAMS__Policy__c> policiesToUpdate =  new List<CanaryAMS__Policy__c>();
      for(wPolicy wPols: selectedPolicies) {
        CanaryAMS__Policy__c Policy = new CanaryAMS__Policy__c();
      
       Policy.CanaryAMS__To_be_Reviewed__c = false;
       Policy.Id = wPols.Pol.Id;
      
       policiesToUpdate.add(Policy);
       }
       system.debug('policiesToUpdate -----'+policiesToUpdate);
       update policiesToUpdate;
    }
   
    public void FirstPage()
{
  policyList = null;
  OffsetSize = 0;
  system.debug('FirstPage OffsetSize === >> '+ OffsetSize);
}
public void previous()
{
   policyList = null;
  OffsetSize = OffsetSize - LimitSize;
  system.debug('previous OffsetSize === >> '+ OffsetSize);
}
public void next()
{
  policyList = null;
  OffsetSize = OffsetSize + LimitSize;
  system.debug('next OffsetSize === >> '+ OffsetSize);
}
public void LastPage()
{
  policyList = null;
  OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
  system.debug('LastPage OffsetSize === >> '+ OffsetSize);
}
public boolean getprev()
{
  //policyList = null;
  if(OffsetSize == 0)
  return true;
  else
  return false;
}
public boolean getnxt()
{
  //policyList = null;
  if((OffsetSize + LimitSize) > totalRecs)
  return true;
  else
  return false;
}

  public Map<Id,String> RecordTypeMap(){
        Map<Id,String>recordTypesMap = new map<Id,String>();
        List<RecordType> recordTypes = null;
        try{
            recordTypes = [Select Id,Name From RecordType];
            for(RecordType info: recordTypes) {
                recordTypesMap.put(info.Id,info.Name);
            }
        }catch (DmlException e) {
               system.debug('error'+e);
                return null;
        }
        return recordTypesMap;
    }    
   
}
VisualForce Page Code
<apex:page controller="PolicyWrapperClassController">

<script>
    var newWin=null;
    function openLookupPopup(name, id)
    {
        var url="/apex/LookupExamplePopup?namefield=" + name + "&idfield=" + id;
        newWin=window.open(url, 'Popup','height=500,width=600,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');
        if (window.focus)
        {
            newWin.focus();
        }
          
        return false;
    }
                
    function closeLookupPopup()
    {
       if (null!=newWin)
       {
          newWin.close();
       }
    }
  
     function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");               
            for(var i=0; i<inputCheckBox.length; i++){       
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){                                  
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
  
</script>
<apex:pageMessages />


    <apex:form >
        <apex:pageBlock id="details" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Merge Policies" action="{!processSelected}" rerender="table"/>
                  <apex:commandButton value="Mark As Resolved" action="{!markAsResolved}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!policies}" var="p" id="table">
                <apex:column >
              
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                    </apex:facet>
                    <!-- This is our selected Boolean property in our wrapper class -->
                    <apex:inputCheckbox value="{!p.selected}" id="inputId"/>
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
              <apex:column headerValue="Policy Name" >
                <apex:outputLink value="/{!p.pol.Id}" id="eventlink" target="_blank"> {!p.pol.Name}
                    </apex:outputLink>
               </apex:column>
                <apex:column headerValue="Policy Number" value="{!p.pol.Policy_Number__c}" />
               <!--  <apex:column headerValue="Contact" >
                    <apex:outputLink value="/{!p.pol.CanaryAMS__Account__r.Primary_Contact__c}" id="eventlink">{!p.con.Name}
                    </apex:outputLink>
                </apex:column> -->
                <apex:column headerValue="Policy Type" value="{!p.recordTypeName}" />
              
               <apex:column headerValue="Carrier" value="{!p.pol.CanaryAMS__Carrier__r.Name}" />
                <apex:column headerValue="Suggested Policy" >
                    <apex:outputPanel >
                        <apex:inputHidden value="{!p.bestMatch.Id}" id="bestMatchId" />
                         <apex:outputLink value="/{!p.bestMatch.Id}" id="eventlink5" target="_blank"> {!p.bestMatch.Name}
                          </apex:outputLink>
                    </apex:outputPanel>
                </apex:column>
                         
              
                <apex:column headerValue="Policy" >
                    <apex:outputPanel >
                        <apex:inputHidden value="{!p.policyId}" id="policyId" />
                        <apex:inputText value="{!p.policyName}" id="policyName" onFocus="this.blur()" /> <a href="#" onclick="openLookupPopup('{!$Component.policyName}', '{!$Component.policyId}'); return false">Lookup</a>
                    </apex:outputPanel>
                </apex:column>
             </apex:pageBlockTable>
           
             <apex:pageblockButtons >
    <apex:commandButton value="First Page" rerender="details" action="{!FirstPage}" disabled="{!prev}"/>
    <apex:commandButton value="Previous" rerender="details" action="{!previous}" disabled="{!prev}"/>
    <apex:commandButton value="Next" rerender="details" action="{!next}" disabled="{!nxt}"/>
    <apex:commandButton value="Last Page" rerender="details" action="{!LastPage}" disabled="{!nxt}"/>
   </apex:pageblockButtons>
           
        </apex:pageBlock>
      
    </apex:form>
 
</apex:page>

Hi,

Is it mandatory to use isCreateable(), isAccessible(), isUpdateable() and isDeleteable() in apex code?
As in my case I have more than 100 fields in an sObject and to get all fileds data I have check isAccessible() on all fields. This does not seem to be the correct way to do this.
Can you please let me know how to do this efficienly or provide a dowumentation on this?

Regards
Abhishek
Hi

I tried to create a webservice using apex in salesforce. But when I am trying to access it from another class it is throwing following error.

[{"errorCode":"NOT_FOUND","message":"Could not find a match for URL /FieldCase"}]

My Webservice Code:
 
@RestResource(urlMapping='/FieldCase')
global with sharing class RESTCaseController {

@HttpGet   
  global static List<Account> createNewCase() {
       List<Account> company = [Select ID, Name, BillingState from Account where Name = 'AproposeInc'];
        return company;
  }
}

Class code in which I am accessing the the webservice
public with sharing class CallRestCaseController {
    
     public Pagereference callAPI()
    {
         ValidaCredenciais('reee ','eeee', null);
         return null;
    }
    
    
    public String ValidaCredenciais(String Usuario, String Senha, String SessionId) {
        try
        { 
       
            HttpRequest req = new HttpRequest();         
            Http http = new Http();         
            req.setMethod('GET');         
            req.setEndpoint('https://salesfoce.instance.name/services/apexrest/FieldCase');         
           // req.setBody('{"usuario": "' + Usuario + '", "senha": "' + Senha + '", "orgId": "' + System.Userinfo.getOrganizationId() + '"}');
            req.setHeader('Content-Type', 'application/json');
            req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
          //  req.setBody('{"companyName":"AproposeInc"}');
            HTTPResponse resp = http.send(req);
            String RetornoValida = resp.getBody();    
           
            system.debug('comingg ============= ???? '+RetornoValida);
            return RetornoValida;
         }
        catch(System.CalloutException e)
        {
        System.debug('Sorry, You have an error ' + e.getMessage());
        }
        return null;
     }

}

I have also added the salesforce instance name in remote sites. But still no success. I am accessing it in the same org.
Please help.

Also I have to access it for another org, then what should I do ??

Thanks in advance !
 

 

Hi

I have added an Iframe in my visual force page. For some sites it is redirecting to the Url itself. This is due to the code used in the wesite to prevent frame brusting.

I tried to use Sandbox=" " property of html5 but it doesn't work.

I also used following javascrippt code.

window.onbeforeunload = function (evt) {    

      return "This will end your session";
}



This image is not available because: You don’t have the privileges to see it, or it has been removed from the system

But it shows an popup box with two buttons stay on page and leave page every time my page refresh. Is there any way to stop this redirection without showing this popup.