• cvuyyuru
  • NEWBIE
  • 335 Points
  • Member since 2011
  • Salesforce Architect


  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 77
    Replies
Im always having problems with the "Programme Area" object. It never seems to want to test and Its always at this point I get stuck.
User-added imageUser-added imageUser-added image
Can somone help me with what im missing and tell me how you knew what I needed and where I needed it thankyou.
If it helps the "Programme Area" is a master Detail.

Thanks Dan
I upload a image and use google vision api ocr it:
public blob file { get; set; }

public void uploadImage()
    {
String b64String = EncodingUtil.base64Encode(file);		
            Http http = new Http();	 
            HttpRequest  request = new HttpRequest();
            request.setMethod('POST');	     
            request.setHeader('Content-Length', '2000');
            request.setHeader('Content-Type', 'application/json');             
            request.setEndpoint('https://vision.googleapis.com/v1/images:annotate?key=AIzaSyDY2VbfNW9rIXOJs9O....');	        
                 
            request.setBody(b64String);	        
            HttpResponse response = http.send(request);	        
            imagetext= response.getBody();
           System.debug(imagetext);
}

Result:
00:01:19.61 (1062397547)|USER_DEBUG|[82]|DEBUG|{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Expected a value.\n/9j/4AAQSkZJRgABAQAA\n^",
    "status": "INVALID_ARGUMENT"
  }
}
How can call google vision api from apex?
Thank you.
 

Hi. I want to create a selectlist exactly like this.

User-added image

I created the logic for this but I really don't know how to make it with Visualforce.

Controller:

 

public class TaskController {
    public List<Task> lstTasksForUser {get;set;}
    public TaskController(){
        lstTasksForUser = [Select id, ActivityDate, Status, Subject, WhoId, WhatId, CompanyName__c, AccountId From Task WHERE Status!= 'Completed' AND OwnerId =: UserInfo.getUserId()];
    }
    
    public List<Task> tasksToday {get;set;}
    public List<Task> getTodayTasks(){
        tasksToday = [Select id, CreatedDate, ActivityDate, Status, Subject, WhoId, WhatId, CompanyName__c, AccountId From Task where ActivityDate = TODAY AND Status!= 'Completed'];
        return tasksToday;
    }
    
    public List<Task> tasksThisMonth {get;set;}
    public List<Task> getThisMonthTasks(){
        tasksThisMonth = [Select id, CreatedDate, ActivityDate, Status, Subject, WhoId, WhatId, CompanyName__c, AccountId From Task where ActivityDate = THIS_MONTH AND Status!= 'Completed'];
        return tasksThisMonth;
    }
    
    public List<Task> tasksCloseTomorow {get;set;}
    public List<Task> getTomorowCloseTasks(){
        tasksCloseTomorow = [Select id, CreatedDate, ActivityDate, Status, Subject, WhoId, WhatId, CompanyName__c, AccountId From Task where ActivityDate = TOMORROW AND Status!= 'Completed'];
        return tasksCloseTomorow;
    }
    
    public List<Task> tasksOverdue {get;set;}
    public List<Task> getOverdueTasks(){
        tasksOverdue = [Select id, CreatedDate, ActivityDate, Status, Subject, WhoId, WhatId, CompanyName__c, AccountId From Task where ActivityDate < TODAY AND Status!= 'Completed' ];
        return tasksOverdue;
    }
    
    
}

This is my VF page and I'm stuck on this selectList part. I want when I select Today in the selectListOptions my pageBlockTable to change and fetch the records for Today.

 

<apex:page controller="TaskController" tabStyle="Task">
    <apex:form >
        <apex:pageBlock title="My Tasks" id="tasks_list">
            <apex:pageBlockTable value="{!lstTasksForUser}" var="tsk">
                <apex:selectList size="5" onchange>
                	<apex:selectOptions value="{!TodayTasks}" >
                        
                    </apex:selectOptions>
                </apex:selectList>
                <apex:column headerValue="Complete" >
                    <a href="https://eu12.salesforce.com/{!tsk.id}/e?close=1&retURL=%2Fhome%2Fhome.jsp" rendered="{!if(tsk.status!='Completed',true,false)}" > 
                        X 
                    </a>
                </apex:column>
                <apex:column value="{!tsk.ActivityDate}"/>
                <apex:column value="{!tsk.Status}"/>
                <apex:column value="{!tsk.Subject}"/>
                <apex:column value="{!tsk.WhoId}"/>
                <apex:column value="{!tsk.WhatId}"/>
                <apex:column value="{!tsk.CompanyName__c}"/>
                <apex:column value="{!tsk.AccountId}"/>
            </apex:pageBlockTable>
        </apex:pageBlock> 
    </apex:form>
</apex:page>
 

 

// Create a list of contacts
List<Contact> conList = new List<Contact> {
        new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
        new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
        new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
        new Contact()};
            
// Bulk insert all contacts with one DML call
Database.SaveResult[] srList = Database.insert(conList, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted contact. Contact ID: ' + sr.getId());
    } else {
        // Operation failed, so get all errors
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Contact fields that affected this error: ' + err.getFields());
	 }
    }
}
I am getting invalid constructor syntax error in anonymous apex. this code is from trailhead in which database method is used.
 
Hi There,

So I am attempting to create a VF page that brings in all Activities onto an Opportunity from the Opportunities Primary Contact that is identified on the Opportunity. I attempted to create a custom controller class to complete this but then learned that you have to use the standard controller i norder to be able to embed the VF section onto SFDC. 

Also unfortunately now you can no longer switch the Controller from a standard controller to a custom controller anymore :( 

Any ideas on how to work around this? I shared the VF page and custom controller below

VF Page:
<apex:page controller="related_activities_from_contacts">
    <apex:form >
        <apex:pageBlock title="Activites with Contacts" id="activites_list">
            <!-- Events List -->
            <apex:pageBlockTable value="{! events }" var="evt">
                <apex:column value="{! evt.ActivityDate }"/>
                <apex:column value="{! evt.ActivityType }"/>
                <apex:column value="{! evt.Description }"/>
                <apex:column value="{! evt.OwnerId }"/>
                <apex:column value="{! evt.PrimaryWhoId }"/>
                <apex:column value="{! evt.Subject }"/>
                <apex:column value="{! evt.WhoId }"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Custom Controller:
public class related_activities_from_contacts {
    // This would be the Id of the Opportunity
    Id OppID = (Id) ApexPages.currentPage().getParameters().get('id');
    // Select only one of those contacts for use in the Contact ID Below
    OpportunityContactRole[] contactRoleArray =
        [select ContactID
         from OpportunityContactRole 
         where OpportunityId =: OppID AND isPrimary = TRUE];
    
    // Id ContactID = contactRoleArray[0];
    public List<ActivityHistory> getEvents() {
        List<ActivityHistory> results = Database.query(
            'SELECT ActivityDate, ActivityType, Description, OwnerId, PrimaryWhoId, Subject, WhoId' +
            'FROM ActivityHistory ' +
            'Where WhoId =' + contactRoleArray[0]
        );
        return results;
    }  
}

 

Hello All,

                       I am new to Force.com and have a very simple question. I have two types of accounts Customers/Carriers(Account object with different record type).

I am trying to add a new button call (Update from Webservice) which calls a static method in my class which calls the webservice and updates the account record.

Since its a standard controller could anyhelp me to where to put the code for that button action. I was able to add the button but not able to add action and code behind.

 

 

2) Account object has a custom field with PickList as Type (u,c,a, etc). After the web call out i get some  values for that account and need to assign to it. How should I assign picklist values to the object

 

Account. Country(picklist) = 'USA;CAN,AUS';

 

Can i do the above or do i need to put in a List<SelectOptions> and assign to it i.e

List<SelectOptions> opt  = new List<SelectionOptions>();

opt.add( new select option ('USA',USA);

opt.add( new select option ('CAN',CAN);

opt.add( new select option ('AUS',AUS);

Account. Country(picklist) = opt ;

 

Any help is much appreciiated.

Hi,  I'm troubleshooting an error users are having withn a force.com web form.   The scenario is as follows:

 

- A user accesses the Force.Com site page

- He/She has many form fields, one of which is a field to browse to a file and to upload/attach this file.

- After selecting the file and hitting "Attach" the web form page refreshes and displays the filename of the file attached.  The file has been attached to the documents folder within SFDC.

 

- What is happening for larger files is that on clicking "attach"  the file is being uploaded to the Documents folder but the user receives an error message as follows in the web page.

 

"Authorization Required

You must first log in or register before accessing this page.
If you have forgotten your password, click Forgot Password to reset it. "

 

The page is a public facing page (not requiring any logins/authorization).  For smaller attachments the page refreshes ok with the new filename added after an attachment is made.  Do you know if there may be settings which is causing this error? As the file attaches/uploads ok to the documents folder I'm guessing there is no issue wtih filesize restrictions.

 

If you have any suggestons/thoughts on this and help would be appreciated.

 

Thanks! 

How can I set a date field to blank/null when using a Case/If statement?

 

IF (Due__c = True,  TODAY() + 7,Due_Date__c = ????)

 

I'm trying to find a way to iterate over my content horizontally for three columns and once the three columns have been reached, the content moves to a new row.

 

I've tried using a panelGrid and repeat control and a combination or html markup and a repeat control, but I can't get the content to break into three separate columns.

 

Here is my VF page using html table and repeat control:

 

<apex:page standardController="Opportunity" extensions="SalesCoachActivityController">
	<apex:form >
		<apex:outputPanel layout="block" style="overflow:auto;height:190px;">
			<table cellpadding="10">
				<tr>
                	<apex:repeat value="{!Activities}" var="act">
                		<td>
                			<apex:outputLink value="{!act.Content_URL__c}" target="_blank">{!act.Name}</apex:outputLink>
                		</td>
					</apex:repeat>
            	</tr>
			</table>
		</apex:outputPanel>
	</apex:form>
</apex:page>

 Is there a way to iterate over a list and display the content into three columns and then break into a new row once you reach the third column until all records have been displayed?

How do we invoke a vf page in sf1 app from other apps?
I have a deep link url, but I want to open the same url in salesforce1. Any ideas?

How can I insert a chatter message to an User from Apex ?

 

I am trying with chattermessage Object.

 

But this is not writeable.

 

 

Else,

 

 

Can I send a link as private feed to my Users? Is it possible?

 

 

How can I send a message to User in Chatter?

 

 

 

 

Guys,

 

I am presently working on Sites.

 

I have 3 picklist fields on Product Object. Let them be as A, B,C.

 

B is Dependednt on A, and C is dependent on B. 

 

I cannot display picklists fields of Product sobject in Sites, as I have only Read permission over that object.

 

So, I decided to display picklist values by calling describe method for field name of every object.

 

I am using

 

 Schema.SObjectField F1 =product2.A;

 List<Schema.PicklistEntry>pv=f1.getdescribe().getpicklistvalues(); 

 

In the same I can get the values of 3 picklists.

But, How can I get the dependencies that exist among them.

 

 

 

 

Thanks,

Charan

Hi,

 

 

I have two batch apex classes which are schedulable. I wrote test classes to them.

 

When I test my code coverage, I am getting 100% code coverage.

 

But when I tried to move these classes to Prod, I am getting test calsses code coverage error.

 

To my surprise, the batch classes are not covered. 63% coverage.

 

 

 

Then I changed  the code and wrote two test classes for two batch classes which are schedulable.

 

No every class is coverd 100% but the aggregate code coverage is 72%.

 

 

 

Cant know what to do. Suggest me with a best solution

 

 

 

 

Regards,

 

Charan

Did any one worked on Metadata API.

 

Please provide me some links other than Salesforce PDF's.

 

I would like to get custom report from Salesforce through Java.

 

Please help me out.

 

Thanks in Advance.

 

 

 

Regards

 

Charan

I am getting a problem with javascript on button click.

I am invoking an Apex class by passing Id's as parameters.

Before this button works fine.

After the Summer'11 release, its not working.

sforce.apex.execute(null) alert pops out.

If I refresh the page, it works well. 

It occurs often.

 

 

I cannot understand Y this happens!!!!! 

 

 

Is anyone facing  the smae problem?

 

 

Whenever I try to execute the Flow, I am getting this error in my debug log.



21.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO 17:21:40.025|EXECUTION_STARTED 17:21:40.025|CODE_UNIT_STARTED|[EXTERNAL]|VisualForce View State 17:21:40.032|CODE_UNIT_FINISHED|VisualForce View State 17:21:40.032|EXECUTION_FINISHED 17:21:40.052|METHOD_ENTRY|[7]|SparkPlugs.SparkPlugs() 17:21:40.052|METHOD_EXIT|[7]|SparkPlugs 17:21:40.057|FATAL_ERROR|Internal Salesforce.com Error

 

 

 

When I try execute my flow:

 

An unhandled fault has occurred while processing the flow. Please contact your system administrator for more information.

 

 


The flow is working correctly in my Flow Designer and when I uploaded it to Salesforce dev login, this problem arises.

 

 

Kindly help me out.

 

 

 

 

Regards,

 

Charan

 

 

We are currently introducing Salesforce (Sales Cloud & Service Cloud) to support our custom CRM system. Therefore, we are looking for senior Salesforce experts with experience in integrating Salesforce in existing infrastructures (REST) with a two-way data synchronization.

Your tasks
  • You are responsible for managing Salesforce in a team and acting as a contact for all technical issues
  • You coordinate customizations and extensions in Salesforce and implement them independently It supports the connection of Salesforce to internal and external systems
  • With your expertise, you can ensure the data quality and integrity of Salesforce data

You bring that with you
  • You have a university degree in computer science or similar or several years of experience in salesforce development
  • You are motivated to work with different departments and to understand their challenges
  • You radiate a confident demeanor and keep a cool head even in heated discussions
  • You have in-depth knowledge of the SalesCloud environment and, ideally, know-how in the ServiceCloud or MarketingCloud

https://caronsale.de/career/
Hi

I have an apex trigger that takes a contact from the contact roles on opportunity, and adds it to a look up field on the opportunity called opportunity_contact__c.

I also need this to then go to another lookup field on the oportunity line items, also called opportunity_contact__c. Can anyone help me with this? Trigger below:
 
trigger MnCopyPrimaryContact on Opportunity (before update) {
    Set<Id> setOfIds = new Set<Id>();
    for (Opportunity o : Trigger.new) {
        if(o.Id!=Null){
            setOfIds.add(o.Id);
        }
    }
    OpportunityContactRole[] contactRoleArray= [select ContactID, isPrimary from OpportunityContactRole where OpportunityId IN :setOfIds  order by isPrimary desc,CreatedDate];
    for (Opportunity o : Trigger.new) {
        if (contactRoleArray.size() > 0) {
            o.Opportunity_contact__c = contactRoleArray[0].ContactID;           
        }else{
            o.Opportunity_contact__c = null;
        }
    }
}

Many Thanks
Conor​
Im always having problems with the "Programme Area" object. It never seems to want to test and Its always at this point I get stuck.
User-added imageUser-added imageUser-added image
Can somone help me with what im missing and tell me how you knew what I needed and where I needed it thankyou.
If it helps the "Programme Area" is a master Detail.

Thanks Dan
Here is my Test class

@isTest
public class accountExplorer_Test {

    private static testMethod void test() {
       
        accountExplorer hadlerObj = new accountExplorer();
        hadlerObj.accountCollect();
        Transaction__c tansObj = new Transaction__c();
        tansObj=accountExplorer.transDeatils();
        accountExplorer.transNameHandler();
    }    
}

Here is Apex Class:
public class accountExplorer {
   public accountExplorer(){
        system.debug('Inside Constructor');
    }
    //Non Static method : Variable declaration
    List<Account> accountCollectVar = new List<Account>();
    
    //Non-Static method declaration and its body : Account details displayer
    public Account accountCollect(){
        accountCollectVar = [SELECT ID, Name, AccountNumber FROM Account WHERE name='addepalli' OR name='katru'];
        system.debug('Account Details in non-statis method:' +accountCollectVar);
        return accountCollectVar[1];
     }
    //Static Method : Variables declaration Note: Static method not allowing variables to be declared inside methoid body??  ?
    Static Set<Transaction__c> transDetailsVar = new Set<Transaction__c>();
    Static List<Transaction__c> transDetailsVarList = new List<Transaction__c>();
    
    //Metho declaration with method body : Displays all transaction names and its type
    public static Transaction__c transDeatils(){
        transDetailsVarList = [SELECT Name, TransactionType__c FROM Transaction__c WHERE TransactionType__c = 'deposit'];
        transDetailsVar.addAll(transDetailsVarList);
        system.debug('Transaction details:'+transDetailsVar);
        return transDetailsVarList[1];
       
    } 
   
   // Static method, with string return type : Display transaction Name
   //Static string transName{get;set;}
    public static string transNameHandler(){
            Transaction__c transObject = new Transaction__c();
            transObject = [SELECT Name from Transaction__c WHERE TransactionType__c = 'deposit' LIMIT 1];
            system.debug('Transaction name :' +transObject.name);
            return transObject.name;
        }
}
 
Here is my Code 
trigger OppAmount on Opportunity (after insert,after update,after delete,after undelete) {
if(Trigger.isInsert || Trigger.isUpdate  || trigger.isUndelete)
{
set<Id> OppId=new Set<Id>();
for(opportunity o:Trigger.new)
{
OppId.add(o.accountid);
}
Decimal i=0;
List<Opportunity> ls=[select amount from opportunity where accountid in:OppId];
List<Account> l=[select id from account where id in:OppId];
List<account> l1=new List<Account>();


for(Opportunity o:ls)
{
if(o.Amount !=null)
{
i=i+(o.Amount);
}
}
for(Account a:l)
{
a.Opportunity_Amount__c=i;
l1.add(a);
}
update l1;
}

if(Trigger.isDelete )
{
Set<Id> accid=new Set<Id>();
for(Opportunity o:Trigger.old)
{
accid.add(o.accountid);
}
List<Account> ls=[select id,Opportunity_Amount__c,(select accountid,amount from opportunities) from account where id in:accid];
list<account> ls2=new list<account>();
decimal i7;
for(Account a:ls)
{

for(opportunity o:a.opportunities)
{

i7= a.Opportunity_Amount__c - (o.Amount);
a.Opportunity_Amount__c=i7;
}

ls2.add(a);
}
update ls2;
}
}

Its Working for insert and Update,but when i delete a particular Opportunity the amount field on trigger is not updating the subtracted value instead it is updating the deleted opportunity amount value
I upload a image and use google vision api ocr it:
public blob file { get; set; }

public void uploadImage()
    {
String b64String = EncodingUtil.base64Encode(file);		
            Http http = new Http();	 
            HttpRequest  request = new HttpRequest();
            request.setMethod('POST');	     
            request.setHeader('Content-Length', '2000');
            request.setHeader('Content-Type', 'application/json');             
            request.setEndpoint('https://vision.googleapis.com/v1/images:annotate?key=AIzaSyDY2VbfNW9rIXOJs9O....');	        
                 
            request.setBody(b64String);	        
            HttpResponse response = http.send(request);	        
            imagetext= response.getBody();
           System.debug(imagetext);
}

Result:
00:01:19.61 (1062397547)|USER_DEBUG|[82]|DEBUG|{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Expected a value.\n/9j/4AAQSkZJRgABAQAA\n^",
    "status": "INVALID_ARGUMENT"
  }
}
How can call google vision api from apex?
Thank you.
 
Hi All,
        my need is that when a child case is created for compliance team to handle,  no notification is received by the compliance team. the tem should receive the notification?
Any suggestion?
hi,

i have a test class.It is throwing error System.Assertexception
Lead newLead = new Lead();
        newLead.LastName='TestName';
        newLead.Company = 'TestCompany';
        newLead.Email='test@test.com';
        newLead.Status ='Open';
        newLead.Cc__c='test@test.com';
        newLead.Description='Subject:TextBody';
        insert newlead;
          
      Messaging.InboundEmail email = new Messaging.InboundEmail() ;
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

        email.plainTextBody = 'teset';
        email.fromAddress = 'test@test.com';
        email.subject = 'Test Lead';
       // email.ToAddress ='test@gmail.com';
        CreateLeadExample  edr = new CreateLeadExample();
        edr.handleInboundEmail(email,env); 

        Test.startTest();
        Messaging.InboundEmailResult result = edr.handleInboundEmail(email, env);
         System.assert(result.success, 'Error processing email...');
        Test.stopTest();
               
        Lead [] leadDb = [SELECT Id FROM Lead where LastName=:email.FromAddress];
       // System.assertEquals (1, leadDb.size(),'Lead was not inserted');
       System.debug('Size'+leadDb.size());
       
        attachment.body = blob.valueOf('my attachment text');
        attachment.fileName = 'text';
        email.binaryAttachments =
        new Messaging.inboundEmail.BinaryAttachment[] { attachment };
        Attachment attach=new Attachment();     
        attach.Name='Test';
        Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
        attach.body=bodyBlob;
        insert attach;

the result.success is getting false.how can i resolve this error

thanks
  • August 07, 2018
  • Like
  • 0
I have successfully wrote a trigger which calculates all the newly completed activities (Email & Call) and update the total number of a custom filed on the lead object. Similary, I would like to do the same for the completed task which are already completed before the trigger was written however unable to get what the code should be. Below is the trigger that I wrote for the calulcated the New Task :

trigger NoOfEmail on task (after insert, after update) {
    id leadid;
    integer inr = 0;
    List <task> leadTask = new List <task>();
    if (trigger.new!= null) {
        for (task t : Trigger.new) {
            leadid = t.WhoId;
        }
    }
    leadTask = [select id, subject, Status from task where whoid=:leadid];
    for(task t : leadTask){
        if ((t.Subject == 'Email' || t.Subject == 'Call') && t.Status == 'Completed'){
            inr = inr+1;
        }
    }
    
    List <lead> led1 = new list <lead> ();
    List <Lead> led = [select id from lead where id = :leadid];
    for (lead l : led){
        led1.add(l);
        l.Number_of_Activity__c = inr;
    }    
    
    if(led1.size()>0){
        update led1;
    }
}
@RestResource(urlMapping='/PortalUser/*')
Global Class rolesException extends Exception {
    @HttpPost   
    global static String CreateNewUser()  
        {             
     
         RestRequest req = RestContext.request;    
         System.debug('RestRequest___: '+ req);     
         RestResponse res = RestContext.response;   
         System.debug('RestResponse___: '+ res);    
         Blob b = req.Requestbody;                 
         Wrapperclss reg = rolesException.parse(b.tostring());
            Savepoint sp = Database.setSavepoint();

         Try{    
               if(reg.firstname==null || reg.firstname=='')
                {
                    throw new rolesException ('enter firstname');
                }
                if(reg.lastname==null || reg.lastname=='')
                {
                    throw new rolesException ('enter lastname');        
                }
                //if(Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}',reg.Email))
                //{                        
                  //     throw new rolesException ('Please enter valid emailid');
                //} 
                
                 if(reg.role==null || reg.role=='')
                 {
                    throw new rolesException('role is required');  
                 }        
                 /*list<contact> sr =[SELECT  lastName, Role__c from Contact where  Role__c=:reg.Role];
                 system.debug('enter@@@'+sr);
                 if(sr.size()<=0)
                 {
                    throw new rolespostportalException('role is requiredee');        
                 }*/
                 
                 list<Role__c>role=[select Name,Type__c from Role__c where type__c =:reg.Role];
                 system.debug('Enter__'+role);
                 if(role[0].type__c == 'Manager')
               {
                   List<Contact> con = [SELECT Id, Name FROM Contact WHERE accountId=:reg.AccountID AND Role__c=:role[0].Id];
                   if(con.size()>0)

                   {
                       throw new rolesException('Manager already exist');
                   }
               }
               if(reg.username!=null || reg.username!='')

                   {

                    List<User> u = [SELECT username FROM User WHERE username =:reg.username];

                    if(u.size()>0)

                   {

                       throw new rolesException('User already exist');
     }

                    }
            
            Contact C1 = new Contact( AccountID =reg.AccountID, firstName = reg.Firstname, lastName =reg.lastname ,email =reg.Email, role__c = role[0].id);
            insert C1;
                User newUser = new User();           
                newUser.Username =reg.username;     
                newUser.LastName = reg.lastname;
                newUser.Firstname = reg.Firstname;
                newUser.Email = reg.Email;      
                newUser.ContactId =C1.id ;
                newUser.Alias =reg.Alias;
                newUser.TimeZoneSidKey = reg.TimeZoneSidKey;
                newUser.LocaleSidKey = reg.LocaleSidKey;
                newUser.EmailEncodingKey = reg.EmailEncodingKey;
                newUser.LanguageLocaleKey = reg.LanguageLocaleKey;
                newUser.CommunityNickname= reg.CommunityNickname;
                newUser.ProfileId= reg.ProfileId;         
                insert newUser;        
                return 'User Created! Id Is: ' + newUser.Id; 
            }
               catch(Exception e)
               {
                    Database.rollback( sp );
                    system.debug('error____:enter valid ID'+e);
                    return e.getMessage();
               }
        }
               global static Wrapperclss parse(string reg) 
               {       
                   return(Wrapperclss)System.json.deserialize(reg,Wrapperclss.class);  
               }   
               global class Wrapperclss  
                {      
                    global String username{get;set;} 
                    global String Firstname{get;set;} 
                    global String LastName{get;set;}     
                    global String Email{get;set;}    
                    global String ContactId{get;set;}   
                    global String Role{get;set;}
                    global String Alias{get;set;}   
                    global String TimeZoneSidKey{get;set;}   
                    global String EmailEncodingKey{get;set;} 
                    global String LanguageLocaleKey{get;set;}
                    global String LocaleSidKey{get;set;}
                    global String CommunityNickname{get;set;}
                    global String ProfileId{get;set;}   
                    global String AccountID{get;set;}   

                }    
          
    }
// Create a list of contacts
List<Contact> conList = new List<Contact> {
        new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
        new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
        new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
        new Contact()};
            
// Bulk insert all contacts with one DML call
Database.SaveResult[] srList = Database.insert(conList, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted contact. Contact ID: ' + sr.getId());
    } else {
        // Operation failed, so get all errors
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Contact fields that affected this error: ' + err.getFields());
	 }
    }
}
I am getting invalid constructor syntax error in anonymous apex. this code is from trailhead in which database method is used.