• mohan s 37
  • NEWBIE
  • 120 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 19
    Questions
  • 13
    Replies
hi friends,

               The following code is not working for delete event in trigger. But it's working fine for after insert and after update events.
I have custom object Revenue__c. It has master detail relationship with Account. I want to update Account field values with revenue field values whenever the revenue is inserted,updated and deleted.Can any one suggest me what is the wrong in the following code
trigger revenuetrigger on Revenue__c(after insert, after update,after delete){
if(trigger.isinsert || trigger.isupdate ){
new RevenueCal().populateRevenu(trigger.new);
}if(trigger.isdelete){
new RevenueCal().populateRevenu(trigger.old);
}
}
Apex class:
public class RevenueCal {
    Map<Id,Account> accmap = new Map<Id,Account>();
   public List<Id> ids = new List<Id>(accmap.keySet());
    public List<Account> childsToupdate = new List<Account>();
    //ids.addAll();
   public map<String,Revenue__c> linkIdMap = new Map<String,Revenue__c>();
    List<Account>listToUpdate = new List<Account>();
    public void populateRevenue(List<Revenue__c> revlist){
        for(Revenue__c rev : revlist){
           linkIdMap.put(rev.Reporting_Link_Id__c, rev);
          
        }
        //update listToupdate;
        for(Account a : [SELECT Id, Name,Link_Id__c,ParentId,Reporting_Link_Id__c,Revenue_Product__c,
                         Revenue_Service__c,Revenue_Cloud__c FROM Account]){
            if(linkIdmap.containsKey(a.Reporting_Link_Id__c)){
                a.Revenue_Product__c = linkIdmap.get(a.Reporting_Link_Id__c).Product_Revenue__c;
                a.Revenue_Service__c = linkIdmap.get(a.Reporting_Link_Id__c).Service_Revenue__c;
                a.Revenue_Cloud__c = linkIdmap.get(a.Reporting_Link_Id__c).Cloud_Revenue__c;
                childsToupdate.add(a);
            }
        }
        try{
        update childsToupdate;
        }Catch(Exception e){
            system.debug('update failes due to:'+e.getMessage());
        }
    }
}
Hi Friends,

                  I am geeting the following issue when i try to check the syntax error on onclick javascript button. "Syntax error &". in the following code. Can any one please help me resolving this issue.
Code:
{!REQUIRESCRIPT(&quot;/soap/ajax/38.0/connection.js&quot;)} 
{!REQUIRESCRIPT(&quot;/soap/ajax/38.0/apex.js&quot;)} 
try 


var partnerType; 
var accList = []; 
var result = sforce.connection.query( 
&quot;Select Id, Name,Account__c,RecordType.Name,Account__r.Partner_Type_New__c FROM custom_c where id=&apos;{!custom__c.Id}&apos; &quot;); 
var iter = new sforce.QueryResultIterator(result); 

while(iter.hasNext()) 

var record=iter.next(); 
partnerType = record.RecordType.Name;
accList.push(record.Account__c); 

if(partnerType==&apos;customer&apos;) 

sforce.apex.execute(&quot;SampleClass&quot;,&quot;sampleMethod1&quot;,{refreshAccList:accList}); 
parent.window.location = &quot;{! URLFOR($Action.custom__c.View,custom__c.Id,null)}&quot;; 
}
else if(partnerType ==&apos;newcustomer&apos;){ 
sforce.apex.execute(&quot;Sampleclass1&quot;,&quot;sampleMethod&quot;,{refAccList:accList}); 
parent.window.location = &quot;{! URLFOR($Action.custom__c.View,custom__c.Id,null)}&quot;; 
}

catch(err){ 
alert(err); 
alert(&quot;System is currently unable to process your request.&quot;); 
}
Hi Friends,

                 I am getting following Issue when try to retrieve code using force.com migration tool."Access is denied". Can any one suggest me what is this Issue.I have copied the force.com migration tool in F drive. I used the following command to retieve 
C:\Users\lenovo>F:

F:\>cd F:\Ant>ant retrieveCode
Access is denied.

F:\>
Hi Fiends,

                 I am using batch apex for inserting the 100000 records but, the following exception throws while executing the batch. System.LimitException: "Too many DML rows:10001". I have tried giving batch size  as low and maximum but in both the cases the it throws the same exception.

global class InsertionOfOneLakhRecords implements database.Batchable<Sobject>,database.stateful{
   public integer count = 0;
  global database.QueryLocator start(database.BatchableContext bc){
    return database.getQueryLocator('select id, Name FROM Contact');
}
global void execute(database.BatchableContext bc, List<Contact> sobj){
    List<Contact> cons = new List<Contact>();
   for(integer i=0; i<100000; i++){
    Contact c = new Contact(LastName = 'test'+i, Email='test@salesforce.com', Phone = '123456');
    count++;
    cons.add(c);
}
    try{
    Database.SaveResult[] result =database.insert(cons);
 }
    catch(exception e){
     system.debug('Exception:'+e.getMessage());
    }
}
global void finish(database.BatchableContext bc){
 system.debug('total:'+count);   
  }
}

Thanks & Regards
Hi Friends,
I am getting following bug while testing my controller "System.QueryException: line 6:730 no viable alternative at character 'a' ". Can any one help how to resolve it. Can any one tell me is the following query is correct or not if it is wrong modify the query and give me reply as correct query your help is really appreciable. I hope i receive reply.
In the following query i am passing SiteIds, procedures and patientage as a string of values dynamically but they are not passed to the query.
I ahve written the query like this
 conditionQuery =     ' AND Patient__r.IsActive__c = true ' +
                             ' AND Patient__r.Site_Id__c IN : siteIds ' +
                             ' AND Patient__c IN : patEnrollTeamIds' +
                             ' AND Patient__r.Patient__r.Gender__c IN : gender ' +
                             ' AND Patient__r.Patient__r.Age_Group__c IN : patientAge ' +
                             ' AND Patient__r.Surgery_Type__c IN : procedures ' +
                             ' AND Patient__r.ASA_Score__c IN : asascore ';

This is debug log:
Final Query :Select Text_Field__c, Patient_Survey__r.Patient__r.Id, Patient_Survey__r.Patient__r.Patient__r.First_Name__c, ER_DOS_Delta__c, Patient_Survey__r.Patient__r.Patient__r.Last_Name__c,LOS__c, Patient_Survey__r.Patient__r.Surgery_Date__c,Number__c, Patient_Survey__r.Patient__r.Surgery_Type__c,Patient_Survey__r.Patient__r.ASA_Score__c, Patient_Survey__r.Patient__r.Patient_Enrollment_Status__c, Patient_Survey__r.Patient__r.Percent_Survey_Completed__c,Patient_Survey__r.Patient__r.Missed_Surveys__c,Patient_Survey__r.Patient__r.Other_Pain_Management_used_if_any__c From Patient_Responses__c WHERE Number__c != null AND IsDemo__c =false AND Question_Pattern__c = 'Group' AND Group_Name__c = 'Pain' AND Patient_Survey__r.Survey_Status__c IN ('Completed', 'In-Progress' , 'Expired') AND Category__c LIKE '%Rest%' AND Patient_Survey__r.Name= 'Post Surgery, day 3' AND Patient_Survey__r.Patient__r.Patient__r.Account__c in :siteIds AND Patient_Survey__r.Patient__c IN : patEnrollTeamIds AND Patient_Survey__r.Patient__r.Surgery_Type__c in :procedures AND Patient_Survey__r.Patient__r.Patient__r.Age_Group__c in :patientAge AND Patient_Survey__r.Patient__r.Patient__r.Gender__c in :gender AND Patient_Survey__r.Patient__r.ASA_Score__c IN : asascore AND DAY_ONLY(Createddate) <=2017-08-10 00:00:00and DAY_ONLY(Createddate) >=2017-01-10 00:00:00 ORDER BY Patient_Survey__r.Name LIMIT 1000
 global class SelectedFilters{
        public Set<String> SiteIds{get;set;}
        public Set<String> surgeonIds{get;set;}
        public Set<string> anesthesiologistIds{get;set;}
        public List<String> procedures{get;set;}
        public List<string> ONQUsed{get;set;}
        public List<string> patientAge{get;set;}
        public List<string> gender{get;set;}
        public string onload {get;set;}
        public List<string> PainManagementUsed{get;set;}
        public List<String> HospitalName {get;set;}
        public List<String> ASAScore {get;set;}
        
        public SelectedFilters(Set<String> siteIds, /*Boolean is_ReadOnlySite,*/
                             Set<String> surgeonIds,Set<String> anesthesiologistIds,
                             List<String> procedures,List<string> ONQUsed,
                             List<string> patientAge,List<string> gender,
                             List<string> PainManagementUsed , List<String> HospitalName,List<String> ASAScore) {
            this.siteIds = siteIds;
            this.surgeonIds = surgeonIds;
            this.anesthesiologistIds = anesthesiologistIds;
            this.procedures = procedures;
            this.ONQUsed= ONQUsed;
            this.patientAge= patientAge;
            this.gender= gender;
            this.PainManagementUsed= PainManagementUsed;
            this.HospitalName = HospitalName;
            this.ASAScore = ASAScore;
        }
==
 JSONstring ='{"siteIds":["'+String.valueof(testAccount.id)+
            '"],"surgeonIds":["' +String.valueof(testContact.id)+
            '"],"anesthesiologistIds":["'+String.valueof(testContact.id) +
            '"],"procedures":["Lap BSO"],"ONQUsed":["Yes"],"patientAge":["0-18","18 – 29"],"gender":["Male","Female"],"PainManagementUsed":["ON-Q","Single Injection nerve block","Wound infusion","Local infiltration"],"HospitalName":["ABC","DEF"],"ASAScore":["I"]}';
      
 if(String.isNotBlank(jsonString))
        {
            EngagementGraphsController.SelectedFilters test  = (EngagementGraphsController.SelectedFilters)JSON.deserialize(jsonString,EngagementGraphsController.SelectedFilters.class);
            system.debug('-----------test :'+test);  
            
            EngagementGraphsController.SelectedFilters currentFilter = EngagementGraphsController.generateFilterWrapper(jsonString);
            Set<String> siteIds = currentFilter.SiteIds;
            Set<String> surgeonIds = currentFilter.surgeonIds;
            Set<String> anesthesiologistIds = currentFilter.anesthesiologistIds;
            List<String> procedures = currentFilter.procedures;
            List<string> painMgmntUsed = currentFilter.PainManagementUsed;
            List<string> patientAge = currentFilter.patientAge;
            List<string> gender = currentFilter.gender;
            List<string> hospital = currentFilter.HospitalName;
            List<string> asascore = currentFilter.ASAScore;
     
Hi Friends,
I am getting the following bug while performing test to the apex controller the test class is failed due to the following error can any one please tell me what it is and how to resolve it. "System.JSONException: Malformed JSON: Expected '{' at the beginning of object"
Class.EngagementGraphsController.generateFilterWrapper: line 253, column 1
Class.ChartDrillDownController.getDrilldownPatientsData: line 39, column 1
Class.ChartDrillDownController_Test.patientdataTest: line 86, column 1
Test class:
/*Developer: Rambabu
Description: This is test class of ChartDrillDowncontroller*/
@istest
public class ChartDrillDownController_Test{
   static Account testAccount;
    static Contact testContact;
     static User user =[SELECT Id, Name from User WHERE Alias='rbabu'];
      static List<Patient_Enrollment__c> enrollmentTestList = new List<Patient_Enrollment__c>();
    static string chartInput='{"xAxis":"2017-08-01","legend":"TOTAL_INVITED","chartName":"PATIENT_ENGAGEMENT"}';
         static String FromDateString = '2017, 01, 01';
        static String ToDateString = '2017, 08, 09';
       static boolean isDemo = true;
      static date startDate = date.newInstance(2016,08,10);
     static date endDate = date.newInstance(2017,08,10);
    Static String JSONstring = '{"siteIds":["001c000001BydRwAAJ"],"surgeonIds":["003c000000ph8dEAAQ"],"anesthesiologistIds":["003c000000ph8cqAAA"],"procedures":["Axillary Dissection", "Bilateral Mastectomy", "Hiatal Hernia Repair", "Hysterectomy with Staging", "Hysteroscopy D&C", "Lap Cholecystectomy", "Lap-assisted Hysterectomy", "Laparoscopic Supracervical Hysterectomy", "Laparotomy", "Liver transplant"],"HospitalName":["ABC","DEF"],"patientAge":["0-18","18 – 29","30 – 39","40 – 49","50 – 59","60 – 69","70 – 79",">80"],"gender":["Male","Female"],"PainManagementUsed":["ON-Q","Single Injection nerve block","Wound infusion","Local infiltration"]}';
    @testSetup static void setupTestData(){
        testAccount = new Account(Name='testAccount',Site_Display_Name__c='testsite',Start_Date__c=startDate,End_Date__c=endDate,Email__c='test@hyh.com',Sales_Rep__c=user.id,Status__c='Active',OwnerId=user.id);
        testContact = new Contact(LastName='contact', FirstName='test',AccountId=testAccount.Id,Email='testmail@hyh.com',Role__c='Surgeon',Surgical_Specialty__c='General Surgery');
        for(integer i=0; i<100; i++){
            Patient_Enrollment__c pe = new Patient_Enrollment__c();
            pe.Patient_First_Name__c = 'enrollment';
            pe.Patient_Last_Name__c = 'test'+i;
            pe.Patient_Phone_Number__c = '02064546025';
            pe.Patient_Email__c = 'patienttestmail@hyh.com';
            pe.Date_of_Birth__c = date.newInstance(1980,05,12);
            if(i<=50){
            pe.Gender__c = 'Male';
            pe.Patient_Enrollment_Status__c = 'Active - Accepted';
            }
            else{
            pe.Gender__c = 'Female';
            pe.Patient_Enrollment_Status__c = 'Active - Invited';
            }
            pe.Surgery_Date__c = date.newInstance(2017,08,1);
            pe.Surgeon__c = testcontact.id;
            pe.Surgery_Type__c = 'Lap BSO';
            pe.Surgeon__c = testContact.Id;
            pe.Anesthesiologist__c = testContact.Id;
            pe.On_Q_Used__c = 'Yes';
            pe.On_Q_pump_Model_used__c = 'CB003';
            pe.Other_Pain_Management_used_if_any__c = 'Wound infusion';
            pe.IsDemo__c = true;
            enrollmentTestList.add(pe);  
    }
            insert enrollmentTestList;
        system.debug('Patient Enrollment List:'+enrollmentTestList.size());
            SurveyTemplate__c template = new SurveyTemplate__c();
             template.Survey_Template_Name__c  = 'test template';
             template.Available_From__c = '1';
             template.Available_To__c = '3';
             template.Survey_Day_Email_Time__c ='8:00';
             template.Email_Reminder_Time__c = '7:00';
             template.SMS_Reminder_Time__c ='6:00';
             template.Survey_Order__c =2;
           insert template;
        system.debug('Template Id:'+template.Id);
             List<Patient_Survey__c> surveyList = new List<Patient_Survey__c>();
             for(integer i=0; i<10; i++){
                Patient_Survey__c ps = new Patient_Survey__c();
                ps.Name = 'test survey'+i;
                ps.IsDemo__c = true;
                ps.Patient__c = enrollmentTestList[i].id;
                ps.Survey_Name__c = template.id;
                surveyList .add(ps);
      }
       insert surveyList;
        system.debug('SurveyList Size:'+surveyList.size());
       List<Patient_Responses__c> surveyResponseList = new List<Patient_Responses__c>();
       for(integer i=0; i<=10; i++){
           Patient_Responses__c psr = new Patient_Responses__c();
           psr.Patient_Survey__c = surveyList[0].id;
           psr.Selected_Medication_List__c = 'Celebrex';
           psr.Opioid__c = true;
           psr.Question_Pattern__c='Dependent';
           psr.Section_Name__c = 'side effects';
           psr.Answer__c = 'Dizziness;Constipation';
           psr.IsDemo__c  = false;
           surveyResponseList.add(psr);
       }
       insert surveyResponseList;
        system.debug('Survey response List size:'+surveyResponseList);
  }
    static testmethod void patientdataTest(){
        system.runAs(user){
          test.startTest();
        ChartDrillDownController.getDrilldownPatientsData(JSONString,chartInput,FromDateString,ToDateString,isDemo);
        //ChartDrillDownController.getDrilldownPatientsDataForOutcome(chartInput,FromDateString,ToDateString,JSONString,isDemo);
        test.stopTest();
        }
     }
}
 
Hi Friends,
I read in apex developer guide we can't deploy the email service address name. Can  any one help me how we deploy the email service address name?
Thank you
Hi Friends,
I have code coverage issue while writing a test class for the trigger. One line is not passed the code coverage I did not find the reason, why it is not .Can any one suggest me the reason. I am getting 87% code coverage.
Trigger:
trigger AccountsProcessorTrig on Account (after insert) {
    if(trigger.isInsert){
       AccountProcessor.countContacts(trigger.newMap.keySet()); 
    }
}
Apex Class:
public class AccountProcessor {
    public static integer count=0;
@future
    public static void countContacts(set<Id> accountids){
        List<Account> accountstobulkify=[SELECT Id, Name FROM Account WHERE Id IN:accountids];
        Map<Id,Account> accountstoupdate=new Map<Id,Account>();
        for(Account a:accountstobulkify){
            for(Contact c:a.Contacts){
                count=count++;// this line is not passed
            } 
        a.Number_Of_Contacts__c=count;
        }
        
     }


Test class:
@isTest
private class AccountProcessorTest {
@isTest
    static void CountNoOfContacts(){
        Account testacc=new Account(Name='Numberofcontactstest',Industry='Finance');
        insert testacc;
        List<Contact> testlist=new List<Contact>();
        for(integer i=0; i<10; i++){
            Contact testcon=new Contact(LastName='AccountContact'+i, AccountId=testacc.id);
            testlist.add(testcon);
        }
        insert testlist;
        system.debug('size:'+testlist.size());
        Map<Id,Account> testids=new Map<Id,Account>([SELECT Id, Name, Number_Of_Contacts__c FROM Account WHERE Name=:'Numberofcontactstest']);
        Set<Id> accids=testids.keySet();
        system.debug('Contcts:'+([SELECT Count() FROM Contact WHERE AccountId=:testacc.Id]));
        test.startTest();
        AccountProcessor.countContacts(accids);
        test.stopTest();
        decimal a=[SELECT ID, Name FROM Account WHERE Name=:'Numberofcontactstest'].Number_Of_Contacts__c;
        system.assertEquals(10, a);
    }
}
 
Hi, Friends
I want to display selected Account record as pdf format when I select the checkboxes those records only displayed in pdf format. I tried this scenario but the page has not displayed the content of the record. it displays only empty pdf page. Please go through the following code which i had developed in my org. Please let me know what mistake I had made in the code.
Controller
public class PdfController {
 public List<Account> initialList {get;set;}
    public List<Account> selectedlist {get;set;}
    public List<InnerWrapper> wlist {get;set;}
    public PdfController() {
      initialList=new List<Account>();
        wlist=new List<InnerWrapper>();
        InnerWrapper iw;
      initialList=[SELECT Id, Name, Industry FROM Account LIMIT 10]; 
        for(Account a:initialList){
            iw=new InnerWrapper();
            iw.unselected=a;
            wlist.add(iw);
        }
    }
    public PageReference displaySelected() {
        selectedlist=new List<Account>();
        for(InnerWrapper selectedaccount:wlist){
            if(selectedaccount.selectacc){
               selectedlist.add(selectedaccount.unselected);
           }
        } 
        PageReference p=page.pdfpage;
        return p;
    }
   
    public class InnerWrapper {
        public boolean selectacc{get;set;}
        public Account unselected {get;set;}
    }
}
Vfpage1
<apex:page controller="PdfController">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable title="Accounts" value="{!wlist}" var="iterate">
            <apex:column headerValue="selectAccount">
                <apex:inputCheckbox value="{!iterate.selectacc}"/>
            </apex:column>
            <apex:column headerValue="Name" value="{!iterate.unselected.Name}"/>
            <apex:column headerValue="Print">
                <apex:commandButton value="download" action="{!displaySelected}"/>
            </apex:column>
        </apex:pageBlockTable>
      </apex:pageBlock>
  </apex:form>
</apex:page>
<apex:page controller="PdfController">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable title="Accounts" value="{!wlist}" var="iterate">
            <apex:column headerValue="selectAccount">
                <apex:inputCheckbox value="{!iterate.selectacc}"/>
            </apex:column>
            <apex:column headerValue="Name" value="{!iterate.unselected.Name}"/>
            <apex:column headerValue="Print">
                <apex:commandButton value="download" action="{!displaySelected}"/>
            </apex:column>
        </apex:pageBlockTable>
      </apex:pageBlock>
  </apex:form>
</apex:page>
Vfpage2
<apex:page controller="PdfController" showHeader="false">
    <apex:pageBlock >   
    <apex:pageBlockTable value="{!selectedlist}" var="a">
   <apex:pageBlockSection columns="2">
       <apex:outputField value="{!a.Name}"/>
        </apex:pageBlockSection>
        </apex:pageBlockTable>
        </apex:pageBlock>
</apex:page>
I am getting the above error while compiling the below code please anybody help me why the error is thrown while compile. I hope you guys respond soon.
myController class
public class DynamicCustomizableListHandler {
   private ApexPages.StandardSetController controller;
   private pageReference savepage;
   private Set<String> selectedNames=new Set<String>();
   private Set<String> unselectedNames=new Set<String>();
   private Set<String> inaccessableNames=new Set<String>();
 public DynamicCustomizableListHandler(ApexPages.StandardSetController controller) {
    this.controller=controller;
    loadFieldsWithVisibility();
 }
    private void loadFieldsWithVisibility() {
     
      Map<String, Schema.SobjectField>fields=Schema.SobjectType.Account.fields.getMap();//error line
        for(string s:fields.keySet()){
           if(s=='Name'){
           unselectedNames.add(s);
           }
           if(!fields.get(s).getDescribe().IsAccessble()){
           inaccessablefields.add(s);
           }
         }
      }
       public List<String> getDisplayFields() {
       List<String> displayfields=new List<String>(selectedNames);
       displayfields.sort();
       return displayfields;
       }
    public pageReference Customize() {
    savepage=ApexPages.CurrentPage();
    return page.CustomizeDynamicList;
    }
    public PageReference show() {
      controller.reset();
      controller.addFields(getDisplayFields());
      return savepage;
      }
      public List<SelectOption> getSelectOptions() {
      return selectoptionsFromSet(selectedNames);
      }
      public List<SelectOption> getUnSelectOptions() {
      return unSelectoptionsFromSet(unselectedNames);
   }
     private List<SelectOption> selectoptionsFromSet(Set<String>opts) {
     List<String> optionsList=new List<String>();
     optionsList.sort();
     List<selectOption> options=new List<selectOption>();
       for(String s:optionsList){
       options.add(new selectOption(s, decorateName(s), inaccessableNames.contains(s)));
       return options;
       }
       }
       private string decoreName(string s) {
       return inaccessableNames.contains(s) ?'*'+s:s;
       }
       public transient List<String> selected {get;set;}
       public transient List<String> unselected {get;set;}
       public void doAdd() {
        moveFields(selected, selectedNames, unSelectedNames);
        }
        public void moveFields(List<String> items, set<String>moveTo, Set<String>removeFrom) {
          for(String s:items){
          if(!inaccessableNames.contains(s)){
          moveTo.add(s);
          removeFrom.remove(s);
          }
          }
        } 
   }
Hi Friends,

I am getting following error in my trigger while ignoring the casesensitive. can any one help me what mistake did i made in the following trigger.
My requirement is to autopopulate Region__c custom field in Account when i give Account billing country. For this requirement I have created custom setting called country_Names__c with country_Region as custom field. without containsIgnoreCase it is working fine but when i try to enter Billingcountry in lowercase the Region__c field is not autopopulated for this i want to ignore the caseinsensitive.
error:"Method does not exist or incorrect signature: [Set<String>].containsIgnoreCase(String)"
trigger:
trigger ReportsAccount on Account (before insert, before update) {
    Map<string,Country_Names__c> countries=Country_Names__c.getAll();//get all the countries
     set<string> countrynames= new set<string>();
    countrynames.addAll(countries.keySet()); // add map country keys to set
    if(trigger.isInsert){
    for(Account a:trigger.new){
        if(countrynames.containsIgnoreCase(a.BillingCountry)){  //error line without ignore case it is working fine
            a.Region__c=countries.get(a.BillingCountry).Country_Region__c;
        }
    } // loop ends
    }
    if(trigger.isUpdate){
        for(Account updateacc: trigger.new){
            if(countrynames.contains(updateacc.BillingCountry)){
              updateacc.Region__c=countries.get(updateacc.BillingCountry).Country_Region__c;  
            }  
        }// loop ends
    }
}
Hi Friends,
I am getting following error while i am saving my page "unknown property AddRowsEx.Wrapper" Any one help me how to resolve this issue.

Apex Class:
public class AddRowsEx {
public class WrapperClass {
        public string name{set;get;}
        public string place{get;set;}
        public string state{get;set;}
        public List<WrapperClass> wrapper{get;set;}
       
        public void addNoOfRows(){
            wrapper=new List<WrapperClass>();
          WrapperClass wrp=new WrapperClass();  
         wrapper.add(wrp);
        }
}
}
visualforce page:
<apex:page controller="AddRowsEx">
    <apex:form>
        <apex:pageBlock id="membAdd1" >                  
        <apex:pageblockSection >
            <apex:pageBlockTable value="{!wrapper}" var="wc">
                <apex:column headerValue="Name">
                    <apex:inputText value="{!wc.name}"/>
                </apex:column>
                <apex:column headerValue="place">
                    <apex:inputText value="{!wc.place}"/>
                </apex:column>
                <apex:column headerValue="state">
                    <apex:inputText value="{!wc.state}"/>
                </apex:column>
            </apex:pageBlockTable> 
            <br/><apex:commandLink value="Rowadd" action="{!addNoOfRows}" reRender="membAdd1"/>        
         </apex:pageblockSection>  
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hi Friends,
I have custom field called NoContact__c It is a decimal data type in Account object,. My requirement is to increment the NoContact__c field each time when i try to insert the contact for associated account.And when i delete the contact that associate with Account, The NoContact__c  filed should be decremented. For this requirement i had written trigger in this trigger inserting operation is working fine but when i try to perform delete operation it throws the following error. Can any one help me what mistake did i made in this trigger.

Error: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: External entry point".

Apex trigger:
    trigger countcontacts on Contact (after insert,before delete) {
      List<Contact>conlist=[SELECT Id,Name,contact.AccountId,Contact.Account.NoContact__c FROM Contact WHERE Id IN:trigger.new];
         List<Account> toupdateaccounts=new List<Account>();
             List<Account> updatedlist=new List<Account>();
          for(Contact c: conlist){
     c.Account.NoContact__c=c.Account.NoContact__c+1;
    updatedlist.add(c.Account);
 }
 update updatedlist;
    if(trigger.isDelete){
      List<Contact> contactstodelete=[SELECT Id,Name,contact.AccountId,Contact.Account.NoContact__c FROM Contact WHERE Id      IN:trigger.old];
      for(Contact deletedcontact:contactstodelete){
       deletedcontact.Account.NoContact__c=deletedcontact.Account.NoContact__c-1;
           toupdateaccounts.add(deletedcontact.Account); 
        }
       update toupdateaccounts;
    }
}
I want to add opportunity Amount to related account AnnualRevenue automatically and i want to remove the Opportunity amount from Account AnnualRevenue when opportunity gets deleted. And I want to update Account AnnualRevenue with updated opportunity amount.To achieve this i am getting following error "Invalid foreign key relationship: Account.Opportunities" could any one please resove this issue.I hope I will get correct code.

This is my trigger:
trigger addoppAmounttoAcct on Opportunity (After insert, After update) {
    public decimal amount=0;
    Map<id,integer> oppmap=new Map<id,integer>();
    List<Account> acc=new List<Account>();
    List<Account> a=[SELECT Id,Name,AnnualRevenue,(SELECT Id,Name, Amount FROM Opportunities) FROM Account];
    if(trigger.isInsert){
    set<Id> oppids=trigger.newMap.keySet();
    Map<Id,Integer> accmap=new Map<Id,Integer>();
    //List<Account> a=[SELECT Id,Name,AnnualRevenue,(SELECT Id,Name, Amount FROM Opportunities) FROM Account];
    List<Opportunity> opplist=[SELECT Id, Name,Amount,Opportunity.AccountId FROM Opportunity WHERE Id IN:oppids];
    //List<Account> acc=new List<Account>();
    for(Account ac:a){
    for(Opportunity o:opplist){
        if(o.AccountId==ac.id){
          ac.AnnualRevenue=ac.AnnualRevenue+o.Amount;
            acc.add(ac);
       }else{
           oppmap.put(o.Id, 1); 
        }
     }
  }
    update acc;
        }
 if(trigger.isUpdate){
   set<Id>updateids=trigger.newMap.keySet();
     List<Opportunity> opplistids=[SELECT Id, Name, Opportunity.AccountId,Opportunity.Account.AnnualRevenue, Amount FROM Opportunity WHERE Id IN:updateids];
        for(Opportunity upopp:opplistids){
            for(Account aid:a){
            if(upopp.AccountId==aid.Id){
                amount=upopp.Amount;
                aid.AnnualRevenue=aid.AnnualRevenue-aid.Opportunities.Amount;// here i am getting error like "Invalid foreign key relationship: Account.Opportunities"
                amount=aid.AnnualRevenue;
              aid.AnnualRevenue=amount+upopp.Amount;
                acc.add(aid); 
                }
            } 
        }
        update acc;
    }

Here my intension is to add opportunity amount to account Annual revenue after inserting the opportunity. And update the Annual revenue with updated  opportunity Amount. when i try to inserting opportunity there is no issue. When i try to perform update opportunity amount the previous amount and updated amount both will be added to the account Annualrevenue but my intension is to update only current updated Amount and remove previous amount from the Account AnnualRevenue.
Example:
i have one Account i.e' account1' if Icreate opportunity i.e 'account1opportunity' for this account with amount as 2000 the account1 Annual revenue is updated as 2000 this is fine, but if update account1opportunity with 4000 the related account1 AnnualRevenue is updated with previous amount i.e, 2000 plus updated Amount 4000 i.e  Annual revenue will be updated as 6000 according to my code. But I want to remove previous 2000 amount and update AnnualRevenue with current updated Amount i.e Annual revenue should be 4000.
I want to get all opportunities that are not assigned any task from last week and i want to display those opportunity names with command link in visualforce page, when i click those opportunities, opportunity details will be displayed for this scenario i am writing some code. In this code  i am fetching all the tasks whatids and store that ids into another list but it throws error like "Incompatible argument type List<Opportunity> for All method on List<Id>" can any one help me to resolve this error.

my class
public class getoppsoftask {
public date d=date.today();
    List<Task> oppids=[SELECT Whatid FROM Task];
     List<Opportunity> opplist=[SELECT ID, Name FROM Opportunity WHERE StageName!='Closed'];
   List<id> opids=new List<id>();
     opids.addAll(opplist);
   
}
 
I want to search a specific account record when i enter a record name  and click search button?  i was written the following code. While compliling the code there is no errors but when i click search button in visualforce page the following query exception throws.
System.QueryException: unexpected token: 'Name'
Error is in expression '{!queryData}' in component <apex:commandButton> in page soqldynamic: Class.DynamicSOQL.queryData: line 24, column 1
Class.DynamicSOQL.queryData: line 24, column 1
my class:
public class DynamicSOQL {
    public string accName{set;get;}
    public string accIndustry{set;get;}
    public List<Account>a{set;get;}
    public void queryData(){
        if(a!=null)
            a.clear();
        string q='select name,Industry from Account WHERE Name=:accName';
        if(accName!=''&&accName!=null&&accIndustry!=''&&accIndustry!=null){
            q=q+'where Name=\''+accName+'\'and Industry=\''+accIndustry+'\'';
        }
        else {
            if(accName!=''&&accName!=null){
           q=q+'where Name=\''+accName+'\''; 
        }
            else{
                if(accIndustry!=''&&accIndustry!=null){
            q=q+'where industry=\''+accIndustry+'\'';
            
        }
            }
            
        }
        a=database.query(q);
    }
    
    }
visualforce page:
<apex:page controller="DynamicSOQL" showHeader="true" sidebar="false">
    <apex:form >
        <apex:pageBlock title="Account Data">
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="submit" action="{!queryData}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="1">
                <apex:pageBlockSectionItem >
                   Enter Name: <apex:inputText title="Enter Name" value="{!accName}"/>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                Enter Industry:<apex:inputText title="Enter Industry" value="{!accIndustry}"/>
                    </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock title="Account Records" rendered="{! !ISNULL(a)}">
        <apex:pageBlockTable value="{!a}" var="b">
            <apex:column value="{!b.Name}"/>
            <apex:column value="{!b.industry}"/>
            </apex:pageBlockTable>
            </apex:pageBlock>
    </apex:form>
</apex:page>
can any one help me what is the mistake that i have made in the code
This is my code
=============
global class BatchApex implements Database.Batchable<sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id from Opportunity');
        
    }
    global void execute(Database.BatchableContext bc,List<Opportunity>scope){
        for(Opportunity o:scope){
            o.Name='sandhya';
        }
    update scope;
}
    global void finish(Database.BatchableContext bc){
            
   Messaging.SingleEmailMessage[] mail=new Messaging.SingleEmailMessage();
        String[] toAddresses=new String[] {'forcesfdcloud@gmail.com'};
            mail.setToAddresses(toAddresses);
        mail.setSubject('sending mail ');
        mail.setPlainTextBody('process completed success fully');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
      
    }
    }
I want to update my opportunities. After updating the opportunities i want to send a mail to the above mentioned address, but it shows error like" Illegal assignment from Messaging.SingleEmailMessage to List<Messaging.SingleEmailMessage>" can any one tell me how to solve this issue.
public class MassEmail{
public void show(){
EmailTemplate et=[select id from EmailTemplate where name ='approve loan'];
Messaging.MassEmailMessage email1=new Messaging.MassEmailMessage();
email1.setTemplateId(et.Id);
Contact c =[select id,email from Contact limit 60];
List<id>whoids=new List<id>{c.id};
email1.setTargetObjectIds(whoids);
    
Messaging.Email[] em=new Messaging.Email[]{email1};
Messaging.sendEmail(em);
}
}
This is my code.My intension is to send email to list of contacts.i am getting list of  emails from contacts.While executing the above code i was get issue like "System.QueryException: List has no rows for assignment to SObject". Can any one find what mistake i have done. 
Hi Friends,
I read in apex developer guide we can't deploy the email service address name. Can  any one help me how we deploy the email service address name?
Thank you
This is my code
=============
global class BatchApex implements Database.Batchable<sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id from Opportunity');
        
    }
    global void execute(Database.BatchableContext bc,List<Opportunity>scope){
        for(Opportunity o:scope){
            o.Name='sandhya';
        }
    update scope;
}
    global void finish(Database.BatchableContext bc){
            
   Messaging.SingleEmailMessage[] mail=new Messaging.SingleEmailMessage();
        String[] toAddresses=new String[] {'forcesfdcloud@gmail.com'};
            mail.setToAddresses(toAddresses);
        mail.setSubject('sending mail ');
        mail.setPlainTextBody('process completed success fully');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
      
    }
    }
I want to update my opportunities. After updating the opportunities i want to send a mail to the above mentioned address, but it shows error like" Illegal assignment from Messaging.SingleEmailMessage to List<Messaging.SingleEmailMessage>" can any one tell me how to solve this issue.
Hi Friends,

                  I am geeting the following issue when i try to check the syntax error on onclick javascript button. "Syntax error &". in the following code. Can any one please help me resolving this issue.
Code:
{!REQUIRESCRIPT(&quot;/soap/ajax/38.0/connection.js&quot;)} 
{!REQUIRESCRIPT(&quot;/soap/ajax/38.0/apex.js&quot;)} 
try 


var partnerType; 
var accList = []; 
var result = sforce.connection.query( 
&quot;Select Id, Name,Account__c,RecordType.Name,Account__r.Partner_Type_New__c FROM custom_c where id=&apos;{!custom__c.Id}&apos; &quot;); 
var iter = new sforce.QueryResultIterator(result); 

while(iter.hasNext()) 

var record=iter.next(); 
partnerType = record.RecordType.Name;
accList.push(record.Account__c); 

if(partnerType==&apos;customer&apos;) 

sforce.apex.execute(&quot;SampleClass&quot;,&quot;sampleMethod1&quot;,{refreshAccList:accList}); 
parent.window.location = &quot;{! URLFOR($Action.custom__c.View,custom__c.Id,null)}&quot;; 
}
else if(partnerType ==&apos;newcustomer&apos;){ 
sforce.apex.execute(&quot;Sampleclass1&quot;,&quot;sampleMethod&quot;,{refAccList:accList}); 
parent.window.location = &quot;{! URLFOR($Action.custom__c.View,custom__c.Id,null)}&quot;; 
}

catch(err){ 
alert(err); 
alert(&quot;System is currently unable to process your request.&quot;); 
}
Hi Friends,

                 I am getting following Issue when try to retrieve code using force.com migration tool."Access is denied". Can any one suggest me what is this Issue.I have copied the force.com migration tool in F drive. I used the following command to retieve 
C:\Users\lenovo>F:

F:\>cd F:\Ant>ant retrieveCode
Access is denied.

F:\>
Hi Fiends,

                 I am using batch apex for inserting the 100000 records but, the following exception throws while executing the batch. System.LimitException: "Too many DML rows:10001". I have tried giving batch size  as low and maximum but in both the cases the it throws the same exception.

global class InsertionOfOneLakhRecords implements database.Batchable<Sobject>,database.stateful{
   public integer count = 0;
  global database.QueryLocator start(database.BatchableContext bc){
    return database.getQueryLocator('select id, Name FROM Contact');
}
global void execute(database.BatchableContext bc, List<Contact> sobj){
    List<Contact> cons = new List<Contact>();
   for(integer i=0; i<100000; i++){
    Contact c = new Contact(LastName = 'test'+i, Email='test@salesforce.com', Phone = '123456');
    count++;
    cons.add(c);
}
    try{
    Database.SaveResult[] result =database.insert(cons);
 }
    catch(exception e){
     system.debug('Exception:'+e.getMessage());
    }
}
global void finish(database.BatchableContext bc){
 system.debug('total:'+count);   
  }
}

Thanks & Regards
Notes / Attachment on opporutnity only then allow to create Opportunity Line Item
i was a trying the below code and getting  an error can anyone please let me know what is the mistake i am doing the error is " Error: Unknown property 'AccountStandardController.Location' " what i could understand from the error is Location is not getting referenced pls help 

<apex:page standardController="Account">
 <apex:form >
  <apex:outputPanel id="locationPicker">
<apex:outputField value="{!Location.country}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
</apex:outputpanel>
  </apex:form>
</apex:page>

I have the following code.
When Subcategory is Retailer Street, another field called Chain should appear but i get the following error in popup: 
ReferenceError: Customer_Seling_Type__c is not defined

Can anyone help me please?
<apex:page standardController="Customer_Seling_Type__c" id="pg">
      <apex:form id="frm">
            <apex:pageBlock title="Javascript Example" id="pgBlock" >
                 <apex:pageBlockSection title="Checkbox Example" id="pbSec"> 
                      <apex:inputField id="cc" value="{!Customer_Seling_Type__c.Subcategory__c}" label="Do not call" onchange="tt(this);"/>
                      <apex:pageBlockSectionItem id="pbsi">
                          <apex:outputLabel value="Languages" id="lblLang" ></apex:outputLabel>
                          <apex:inputField id="languageCtrl" value="{!Customer_Seling_Type__c.Chain__c}" />
                      </apex:pageBlockSectionItem>
                 </apex:pageBlockSection>
            </apex:pageBlock>
      
      </apex:form>

      <script>
         function tt(chkboxCtrl) {
         
             try {
                      // hide if checked
                      if( Customer_Seling_Type__c.Subcategory__c =="Retailer Street" ) {
                          document.getElementById('{!$Component.frm.pgBlock.pbSec.pbsi.languageCtrl}').style.display = 'inline';
                          document.getElementById('{!$Component.frm.pgBlock.pbSec.pbsi.lblLang}').style.display = 'inline';
                      }
                      else {
                          document.getElementById('{!$Component.frm.pgBlock.pbSec.pbsi.languageCtrl}').style.display = 'none';
                          document.getElementById('{!$Component.frm.pgBlock.pbSec.pbsi.lblLang}').style.display = 'none';
                      }
                      
                      
              }
              catch(e) {
                  alert(e);
              }
         }
         
         document.getElementById('{!$Component.frm.pgBlock.pbSec.pbsi.languageCtrl}').style.display = 'none';
         document.getElementById('{!$Component.frm.pgBlock.pbSec.pbsi.lblLang}').style.display = 'none';
         
   </script>   
</apex:page>



 
Hi Friends,
I have code coverage issue while writing a test class for the trigger. One line is not passed the code coverage I did not find the reason, why it is not .Can any one suggest me the reason. I am getting 87% code coverage.
Trigger:
trigger AccountsProcessorTrig on Account (after insert) {
    if(trigger.isInsert){
       AccountProcessor.countContacts(trigger.newMap.keySet()); 
    }
}
Apex Class:
public class AccountProcessor {
    public static integer count=0;
@future
    public static void countContacts(set<Id> accountids){
        List<Account> accountstobulkify=[SELECT Id, Name FROM Account WHERE Id IN:accountids];
        Map<Id,Account> accountstoupdate=new Map<Id,Account>();
        for(Account a:accountstobulkify){
            for(Contact c:a.Contacts){
                count=count++;// this line is not passed
            } 
        a.Number_Of_Contacts__c=count;
        }
        
     }


Test class:
@isTest
private class AccountProcessorTest {
@isTest
    static void CountNoOfContacts(){
        Account testacc=new Account(Name='Numberofcontactstest',Industry='Finance');
        insert testacc;
        List<Contact> testlist=new List<Contact>();
        for(integer i=0; i<10; i++){
            Contact testcon=new Contact(LastName='AccountContact'+i, AccountId=testacc.id);
            testlist.add(testcon);
        }
        insert testlist;
        system.debug('size:'+testlist.size());
        Map<Id,Account> testids=new Map<Id,Account>([SELECT Id, Name, Number_Of_Contacts__c FROM Account WHERE Name=:'Numberofcontactstest']);
        Set<Id> accids=testids.keySet();
        system.debug('Contcts:'+([SELECT Count() FROM Contact WHERE AccountId=:testacc.Id]));
        test.startTest();
        AccountProcessor.countContacts(accids);
        test.stopTest();
        decimal a=[SELECT ID, Name FROM Account WHERE Name=:'Numberofcontactstest'].Number_Of_Contacts__c;
        system.assertEquals(10, a);
    }
}
 
Hi, Friends
I want to display selected Account record as pdf format when I select the checkboxes those records only displayed in pdf format. I tried this scenario but the page has not displayed the content of the record. it displays only empty pdf page. Please go through the following code which i had developed in my org. Please let me know what mistake I had made in the code.
Controller
public class PdfController {
 public List<Account> initialList {get;set;}
    public List<Account> selectedlist {get;set;}
    public List<InnerWrapper> wlist {get;set;}
    public PdfController() {
      initialList=new List<Account>();
        wlist=new List<InnerWrapper>();
        InnerWrapper iw;
      initialList=[SELECT Id, Name, Industry FROM Account LIMIT 10]; 
        for(Account a:initialList){
            iw=new InnerWrapper();
            iw.unselected=a;
            wlist.add(iw);
        }
    }
    public PageReference displaySelected() {
        selectedlist=new List<Account>();
        for(InnerWrapper selectedaccount:wlist){
            if(selectedaccount.selectacc){
               selectedlist.add(selectedaccount.unselected);
           }
        } 
        PageReference p=page.pdfpage;
        return p;
    }
   
    public class InnerWrapper {
        public boolean selectacc{get;set;}
        public Account unselected {get;set;}
    }
}
Vfpage1
<apex:page controller="PdfController">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable title="Accounts" value="{!wlist}" var="iterate">
            <apex:column headerValue="selectAccount">
                <apex:inputCheckbox value="{!iterate.selectacc}"/>
            </apex:column>
            <apex:column headerValue="Name" value="{!iterate.unselected.Name}"/>
            <apex:column headerValue="Print">
                <apex:commandButton value="download" action="{!displaySelected}"/>
            </apex:column>
        </apex:pageBlockTable>
      </apex:pageBlock>
  </apex:form>
</apex:page>
<apex:page controller="PdfController">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable title="Accounts" value="{!wlist}" var="iterate">
            <apex:column headerValue="selectAccount">
                <apex:inputCheckbox value="{!iterate.selectacc}"/>
            </apex:column>
            <apex:column headerValue="Name" value="{!iterate.unselected.Name}"/>
            <apex:column headerValue="Print">
                <apex:commandButton value="download" action="{!displaySelected}"/>
            </apex:column>
        </apex:pageBlockTable>
      </apex:pageBlock>
  </apex:form>
</apex:page>
Vfpage2
<apex:page controller="PdfController" showHeader="false">
    <apex:pageBlock >   
    <apex:pageBlockTable value="{!selectedlist}" var="a">
   <apex:pageBlockSection columns="2">
       <apex:outputField value="{!a.Name}"/>
        </apex:pageBlockSection>
        </apex:pageBlockTable>
        </apex:pageBlock>
</apex:page>
Hi Friends,

I am getting following error in my trigger while ignoring the casesensitive. can any one help me what mistake did i made in the following trigger.
My requirement is to autopopulate Region__c custom field in Account when i give Account billing country. For this requirement I have created custom setting called country_Names__c with country_Region as custom field. without containsIgnoreCase it is working fine but when i try to enter Billingcountry in lowercase the Region__c field is not autopopulated for this i want to ignore the caseinsensitive.
error:"Method does not exist or incorrect signature: [Set<String>].containsIgnoreCase(String)"
trigger:
trigger ReportsAccount on Account (before insert, before update) {
    Map<string,Country_Names__c> countries=Country_Names__c.getAll();//get all the countries
     set<string> countrynames= new set<string>();
    countrynames.addAll(countries.keySet()); // add map country keys to set
    if(trigger.isInsert){
    for(Account a:trigger.new){
        if(countrynames.containsIgnoreCase(a.BillingCountry)){  //error line without ignore case it is working fine
            a.Region__c=countries.get(a.BillingCountry).Country_Region__c;
        }
    } // loop ends
    }
    if(trigger.isUpdate){
        for(Account updateacc: trigger.new){
            if(countrynames.contains(updateacc.BillingCountry)){
              updateacc.Region__c=countries.get(updateacc.BillingCountry).Country_Region__c;  
            }  
        }// loop ends
    }
}
Hi Friends,
I have custom field called NoContact__c It is a decimal data type in Account object,. My requirement is to increment the NoContact__c field each time when i try to insert the contact for associated account.And when i delete the contact that associate with Account, The NoContact__c  filed should be decremented. For this requirement i had written trigger in this trigger inserting operation is working fine but when i try to perform delete operation it throws the following error. Can any one help me what mistake did i made in this trigger.

Error: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: External entry point".

Apex trigger:
    trigger countcontacts on Contact (after insert,before delete) {
      List<Contact>conlist=[SELECT Id,Name,contact.AccountId,Contact.Account.NoContact__c FROM Contact WHERE Id IN:trigger.new];
         List<Account> toupdateaccounts=new List<Account>();
             List<Account> updatedlist=new List<Account>();
          for(Contact c: conlist){
     c.Account.NoContact__c=c.Account.NoContact__c+1;
    updatedlist.add(c.Account);
 }
 update updatedlist;
    if(trigger.isDelete){
      List<Contact> contactstodelete=[SELECT Id,Name,contact.AccountId,Contact.Account.NoContact__c FROM Contact WHERE Id      IN:trigger.old];
      for(Contact deletedcontact:contactstodelete){
       deletedcontact.Account.NoContact__c=deletedcontact.Account.NoContact__c-1;
           toupdateaccounts.add(deletedcontact.Account); 
        }
       update toupdateaccounts;
    }
}
I want to search a specific account record when i enter a record name  and click search button?  i was written the following code. While compliling the code there is no errors but when i click search button in visualforce page the following query exception throws.
System.QueryException: unexpected token: 'Name'
Error is in expression '{!queryData}' in component <apex:commandButton> in page soqldynamic: Class.DynamicSOQL.queryData: line 24, column 1
Class.DynamicSOQL.queryData: line 24, column 1
my class:
public class DynamicSOQL {
    public string accName{set;get;}
    public string accIndustry{set;get;}
    public List<Account>a{set;get;}
    public void queryData(){
        if(a!=null)
            a.clear();
        string q='select name,Industry from Account WHERE Name=:accName';
        if(accName!=''&&accName!=null&&accIndustry!=''&&accIndustry!=null){
            q=q+'where Name=\''+accName+'\'and Industry=\''+accIndustry+'\'';
        }
        else {
            if(accName!=''&&accName!=null){
           q=q+'where Name=\''+accName+'\''; 
        }
            else{
                if(accIndustry!=''&&accIndustry!=null){
            q=q+'where industry=\''+accIndustry+'\'';
            
        }
            }
            
        }
        a=database.query(q);
    }
    
    }
visualforce page:
<apex:page controller="DynamicSOQL" showHeader="true" sidebar="false">
    <apex:form >
        <apex:pageBlock title="Account Data">
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="submit" action="{!queryData}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="1">
                <apex:pageBlockSectionItem >
                   Enter Name: <apex:inputText title="Enter Name" value="{!accName}"/>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                Enter Industry:<apex:inputText title="Enter Industry" value="{!accIndustry}"/>
                    </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock title="Account Records" rendered="{! !ISNULL(a)}">
        <apex:pageBlockTable value="{!a}" var="b">
            <apex:column value="{!b.Name}"/>
            <apex:column value="{!b.industry}"/>
            </apex:pageBlockTable>
            </apex:pageBlock>
    </apex:form>
</apex:page>
can any one help me what is the mistake that i have made in the code