• TechEd_Programmer
  • NEWBIE
  • 35 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 26
    Questions
  • 31
    Replies
I have a flag in my Aura:if that allows me to add columns to my interface. I am able to access the controller, however, it does not appear to be updating the flag.

Component Code:
<aura:if isTrue="{!(not(v.showYear4))}">
                    	<lightning:buttonIcon name="4" iconName="utility:add" title="Add Year 4" onclick="{!c.addColumn}" />
                    </aura:if>
                </th>
                <aura:if isTrue="{!v.showYear4}">
                    <th scope="col">
                        <span class="slds-truncate" title="YR4">Year 4</span>
                    </th>
                </aura:if>
Controller Code:
addColumn : function(component, event, helper){
    	
        console.log("made it here");
        var currentTarget = event.currentTarget;
        var currentYear = currentTarget.getAttribute("name");
        component.set("v.showYear"+currentYear,true);
        console.log("v.showYear"+currentYear);
        
    }

Any help wouldd be appreciated. The code is not displaying the second console.log statement but is displaying "made it here"


 
As I need to filter out specific activities from a list, I am attempting to create the ActivityHistory and Open Activity component for a Lightning Page.

I understand how to display lists when they are different objects, however, when I am querying form the same object I am struggling with determining how to display each list where I want.

APEX Controller:
public with sharing class CH_Activity_Viewer_Controller {
@AuraEnabled
public static List<WorkOrder> getOpenAvtivities(Id recordId)
{
    System.debug(recordId);
    return [SELECT Id, (SELECT Id, Subject, Who.Name, StartDateTime, DurationInMinutes FROM OpenActivities) FROM WorkOrder WHERE Id = :recordId];
}

@AuraEnabled
public static List<WorkOrder> getActivityHistory(Id recordId)
{
    System.debug(recordId);
    return [SELECT Id, (SELECT Id, Subject, Who.Name, StartDateTime, DurationInMinutes FROM ActivityHistories) FROM WorkOrder WHERE Id = :recordId];
}
}

Lightning Controller
({
loadInterface : function(component, event, helper)
{
    $( function()
    {
        $( "#accordion" ).accordion();
    });
},

doInit : function(component, event, helper)
{
    var action1 = component.get("c.getOpenAvtivities");
    var action2 = component.get("c.getActivityHistory");
    action1.setParams({
        "recordId" : component.get("v.recordId")
    });
    action1.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            //update all the action1 attributes in the component.
            component.set("v.action1",response.getReturnValue());               
        }
        else if (state === "ERROR") {
            var errors = response.getError();
            if (errors) {
                if (errors[0] && errors[0].message) {
                    console.log("Error message: " + 
                             errors[0].message);
                }
            } else {
                console.log("Unknown error");
            }
        }
    });
    action2.setParams({
        "recordId" : component.get("v.recordId")
    });
    action2.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            //update all the action2 attributes in the component.
            component.set("v.action2",response.getReturnValue());               
        }
        else if (state === "ERROR") {
            var errors = response.getError();
            if (errors) {
                if (errors[0] && errors[0].message) {
                    console.log("Error message: " + 
                             errors[0].message);
                }
            } else {
                console.log("Unknown error");
            }
        }
    });

    $A.enqueueAction(action1);
    $A.enqueueAction(action2);
}  
})

Component
<aura:component controller="CH_Activity_Viewer_Controller" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
<ltng:require scripts="/resource/ActivityViewer/ActivityViewer/jquery-3.2.1.min.js,/resource/ActivityViewer/ActivityViewer/jquery-ui.js" afterScriptsLoaded="{!c.loadInterface}"/>
<ltng:require styles="/resource/ActivityViewer/ActivityViewer/jquery-ui.css"/>
<aura:attribute name="action1" type="WorkOrder[]" />
<aura:attribute name="action2" type="WorkOrder[]" />
<aura:attribute name="recordId" type="Id" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />



<div id="accordion">
    <h3>Open Activities</h3>
    <div>
        <aura:iteration var="wo1" items="{!v.action1}" >
            <aura:iteration var="act1" items="{!wo1.OpenActivities}" >
            <p><b>{!act1.Subject}</b></p>
            <p>{!act1.Who.Name}</p>
            <p>{!act1.StartDateTime}</p>
            <p>{!act1.DurationInMinutes} MIN</p>
            </aura:iteration>
        </aura:iteration>
    </div>
    <h3>Activity History</h3>
    <div>
        <aura:iteration var="wo2" items="{!v.action2}" >
            <aura:iteration var="act2" items="{!wo2.OpenActivities}" >
            <p><b>{!act2.Subject}</b></p>
            <p>{!act2.Who.Name}</p>
            <p>{!act2.StartDateTime}</p>
            <p>{!act2.DurationInMinutes} MIN</p>
            </aura:iteration>
        </aura:iteration>
    </div>
</div>

Any Help is greatly appreciated.​
I am struggling with how to get my component to render a list item that leverages a jQuery library. I have found that when I troubleshoot in the JAVA script console, I can get the function to work properly, however, other than that it will not work. I have seen several posts about render and rerender, but nothing seems to fit what I am attempting to do in this instance.

To explain: I have my main component passing a variable through an event to a component withing the application. Once the event fires, I am running a query and presenting a list of draggable items. The styling for the items render from the library, however the draggable ability is not there without the use of the troubleshooting. I have verified that the data is being passed correctly as well as the fact that all libraries are loading from static resources

Here is my component:
<aura:component controller="Evolve_lgt_Controller">
<aura:attribute name="userstory" type="object"/>
<aura:attribute name="sprint" type="object"/>
<aura:handler event="c:RefreshUserStories" action="{!c.list_Story_sprint}"/>
<style type="text/css">
li.draggable-story { width: 75px; height: 75px; padding: 0.5em; float: left; margin: 5px 5px 5px 5px; border-style: solid; text-align: center; list-style: none;}
#droppable { width: 200px; height: 400px; padding: 0.5em; float: left; margin: 10px; list-style: none; border-style: solid;}
</style>
<div class="userstory">
    <ul id="draggable">
        <aura:iteration items="{!v.userstory}" var="us">
            <li class="draggable-story ui-state-default">
                <p><ui:outputText value="{!us.Name}"/></p>
            </li>
        </aura:iteration>
    </ul>   
</div>

And here is my controller:
({
list_Story_sprint: function(component, event, helper) {
    var story = event.getParam("userstory");
    var sprint = event.getParam("sprint");
    helper.getStories(component, story);
    helper.getSprints(component, sprint);
    //$(document).ready(function() { 
        console.log($( "li.draggable-story" ).length);
        $( "li.draggable-story" ).draggable();
        $( "#droppable" ).droppable({
            drop: function( event, ui ) {
                $( this )
                .addClass( "ui-state-highlight" )
                .find( "p" );
            }
        });
    //});
},
})

Any assistance is appreciated.
All -

I am trying to create a custom button for the Sales console. This button is calling a specific E-Mail Template and prepopulating data.

I know how to leverage the JavaScript for Custom Buttons that bring up web pages or links for the Salesforce Console, but when I try to combine that functionality with the JavaScript to auto select a template for e-mail I get the following error:

Unexpected token ILLEGAL

Here is my code......what am I missing here?

srcUp('
         location.replace('
                /email/author/emailauthor.jsp?retURL=/{!Case.Id}&p3_lkid={!Case.Id}&rtype=003&p2_lkid={!Case.ContactId}&template_id=00XG0000001bHA9/
         ');
    ');


I have a VF Page that simply displays two graphs that I have created for display. The controller for this is an extension. I am not great with Test Code Coverage, so I was hoping for some help. My class is below:
public with sharing class TestResultGraphConroller {

    public string strTrial;
 
    public TestResultGraphConroller(ApexPages.StandardController stdController){
        strTrial = ApexPages.currentPage().getParameters().get('Id');
    }
   
   
    public String getTimeVolume(){
        return getTimeVolume(null);
    }
   
    public String getTimeVolume(List<Id> ids){
        GoogleViz gv = new GoogleViz();             
        gv.cols = new list<GoogleViz.col> {
            new GoogleViz.Col('col2','Interval','number'),
            new GoogleViz.Col('col1','Channel Volume','number')
            };
        decimal interval = 0;
       
        for(Trial__c tv : [Select Id, DisplayChannelVolume__c, TimeZeroOffset__c from Trial__c where Id = :strTrial limit 1])
        {
          String x = tv.DisplayChannelVolume__c;
          List<String> channelvolumevalues = x.split(' ');
         
          interval = tv.TimeZeroOffset__c;
         
          for(String cv: channelvolumevalues)
          {
            GoogleViz.row r = new GoogleViz.row();
            r.cells.add ( new GoogleViz.cell( interval));//interval
            r.cells.add ( new GoogleViz.cell( cv ));//X-Axis
            gv.addRow( r );
            interval = interval + .04;
            }
        }
        return gv.toJsonString();
    }
   
    public String getFlowVolume(){
        return getFlowVolume(null);
    }
   
  public String getFlowVolume(List<Id> ids){
        GoogleViz gv = new GoogleViz();             
        gv.cols = new list<GoogleViz.col> {
            new GoogleViz.Col('col1','Channel Volume','number'),
            new GoogleViz.col('col2','Channel Flow','number')   
            };             
              
        for(Trial__c tfv : [Select Id, DisplayChannelFlow__c, DisplayChannelVolume__c From Trial__c where Id = :strTrial limit 1])
        {                                                         
            String x = tfv.DisplayChannelVolume__c;
            String y = tfv.DisplayChannelFlow__c;
            List<String> channelvolumevalues = x.split(' ');
            List<String> channelflowvalues = y.split(' ');
           
            for(integer i=0; i< channelvolumevalues.size(); i++) //iterate using an integer
            {
              String cv = channelvolumevalues[i]; //get the element at the ith position
              String cf = channelflowvalues[i]; //get matching element at the ith position
              GoogleViz.row r = new GoogleViz.row();
              r.cells.add ( new GoogleViz.cell( cv ));//Y-Axis
              r.cells.add ( new GoogleViz.cell( cf ));//X-Axis
              gv.addRow( r );
            }
        }

        return gv.toJsonString();
    }
}

And my Test Class:

@isTest
public class testTestResultGraphConroller {

    private static testMethod void testTestResultGraphConroller() {
    
     Trial_Session__c tts1 = new Trial_Session__c();
     tts1.Lab__c = 'Test1';
    
     insert tts1;
    
     Trial__c tt1 = new Trial__c();
        tt1.Channel_Flow__c = '0.123456789 0.223456789';
        tt1.Channel_Flow_2__c = '0.423456789 0.523456789 0.623456789';    
     tt1.Channel_Volume__c = '0.123456789 0.223456789';
        tt1.Channel_Volume_2__c = '0.423456789 0.523456789 0.623456789';    
     tt1.DisplayChannelFlow__c = '-0.01114792 0.0204 0.051 0.0714 0.0918';
     tt1.DisplayChannelVolume__c = '0.9639643 0.9641174 0.9645764 0.9652394 0.9661258';
     tt1.TimeZeroOffset__c = 12.0;
     tt1.Trial_Session__c = tts1.Id;
    
     insert tt1;   
    
     Test.startTest();
    
     ApexPages.currentPage().getParameters().put('Id',tts1.Id);
     ApexPages.Standardcontroller stdTrialSession = new ApexPages.Standardcontroller(tts1);
     TestResultGraphConroller trgc = new TestResultGraphConroller(stdTrialSession);
    
     trgc.getFlowVolume();
     trgc.getFlowVolume(??????);
     trgc.getTimeVolume();
     trgc.getTimeVolume(??????);
    
     Test.stopTest();
    }
}

I am not sure what to write into the ??????'s

Thank you for your help.

I am trying to do something in Apex that I think is possible, but I cannot quite grasp how.

 

I have a parent object that has 5 fields.

Field_1__c

Field_2__c

Field_3__c

Field_4__c

Field_5__c

 

These five fields can be populated by "Red", "Yellow" or "Green".

 

The child object has a picklist where the values are the name of the five fields. 

Picklist__c:

Field 1

Field 2

Field 3

Field 4

Field 5

 

If the picklist is not null and one of the field names are selected(with other logic to determine color), I need to populate the corresponding field with the appropriate value.

 

I know somehow this can be accomplished through Dynamic SOQL, but am at a loss at this point. 

 

Please help.

 

So here is the business case:

 

If an opportunity is ia a mature stage, prevent the deletion of all contact roles.

 

Here is the code I created to accomplish this goal. I need to stop the deletion from occuring on teh COntact Rols, but cannot write triggers on contact role. The below controller is associated to a VF Page to get it to run taht is hiddien in the standard layout.

 

public with sharing class CROppHelper {
	
	public Opportunity opp;
	public CROppHelper( ApexPages.StandardController stdController ) {
        opp = ( Opportunity )stdController.getRecord();        
    }
    public void rollupOppContactRole(){
        CROppHelper.rollupOppContactRoleFuture(opp.Id);
    }
    @future public static void rollupOppContactRoleFuture( Id oppId ) 
    {
    	Integer priCnt;
        OpportunityContactRole[] oppRoleList = [SELECT ContactId, IsPrimary FROM OpportunityContactRole
                                         WHERE OpportunityId = :oppId];
        Opportunity opp = [Select ID from Opportunity where Id =: oppId];
        If(oppRoleList.size() > 0)
        {
        	for( OpportunityContactRole oppRole : oppRoleList ) 
        	{
        		if(oppRole.IsPrimary == TRUE)
        		{
        			priCnt = 1;
        		}
        	
        		if(priCnt == 1)
        		{
        			opp.addError('Opportinuty must have a Primary Contact Role in order to be in this stage.');
        		}
        	}
        }
        update opp;
    }
}

VF Page

<apex:page standardController="Opportunity" extensions="CROppHelper" action="{!rollupOppContactRole}"/>

 

 

 When a CR is deleted the code is being triggered to run, but it is not preventing the deletion, nor is it displaying the error on the opportunity. Can I have some assistance please?

All I am currently creating an SDL for CLI Dataloader and I am having an issue resolving one mapping. I want to upsert Events that are related to Opportunities using the opportunity external ID. I have done this with Opportunities to accounts, but it is not working with WhatID to Opportunity External ID.

 

Any suggestions?

So I cannot seem to figure this one out. I do not use maps all that often and I am having a hard time determining how to update a value from it.

 

I am trying to update the inventory by subtracting the value from the map. Pleas see the code below:

trigger PO_Request_Update_Inv_Transit on PO_Request__c (after update) {

	PO_Request__c[] porequest;
	
	Set<Id> poSet = new Set<Id>();
	Set<Id> podetailSet = new Set<Id>();
	Set<Id> inventorySet = new Set<Id>();
	Map<String, Decimal> popartMap = new Map<String, Decimal>();
	List<Inventory__c> inventoryList = new List<Inventory__c>();
	List<PO_Request_Detail__c> porequestdetailList = new List<PO_Request_Detail__c>();
	
	for(PO_Request__c po:porequest)
	{
		poSet.add(po.Id);
		Decimal invQty = 0;
		
		If(po.PO_Req_Status__c == 'Approved')
		{
			porequestdetailList = [Select Id, PO_Request__c, Part_Num__c, Qty__c from PO_Request_Detail__c where PO_Request__c IN : poSet];
			
			for(PO_Request_Detail__c prd:porequestdetailList)
			{
				popartMap.put(prd.Part_Num__r.Id, prd.Qty__c);
				podetailSet.add(prd.Part_Num__c);
			}
			
			inventoryList = [Select Part_Num__r.Id, Qty__c from Inventory__c where Part_Num__c IN :podetailSet];
			
			for(Integer i = 0; i < inventoryList.size(); i++)
			{
				if(popartMap.containsKey(inventoryList[i].Part_Num__r.Id))
				{
					inventoryList[i].Qty__c = inventoryList[i].Qty__c - 
				}
				update inventoryList;
			}
		}
	}
}

 My main problem is how to get the mapped value and use it in my calculation to update.

 

inventoryList[i].Qty__c = inventoryList[i].Qty__c - ???

 

Thank you for your help.

Below is the Batch Job I have created. I am a litle fuzzy as to how to implement this in the shceduler. Can someone assist?

 

global class UpdateContactFlags implements Schedulable, Database.Batchable<sObject>{
	public string query = 'SELECT Id, Contact.Id, Campaign.Fund_s__c, Campaign.Listing_Tactic__c, Status from CampaignMember';
		
	global Database.Querylocator start(Database.BatchableContext BC)
	{
		
		return Database.getQueryLocator(query);
	}
	
	global void execute(SchedulableContext SC)
	{
		UpdateContactFlags ucfg = new UpdateContactFlags();
		database.executebatch(ucfg, 100);
	}
	
	global void execute(Database.BatchableContext BC, List<sObject> scope)
	{
	Set<id> liContIds = new Set<id>();

	for(sObject s : scope){
		CampaignMember cm = (CampaignMember)s;

		if(cm.Campaign.Fund_s__c == 'FSIC' && cm.Campaign.IsActive == TRUE && cm.Campaign.Listing_Tactic__c == 'Major Market Roadshow')
			liContIds.add(cm.Contact.Id);
		}

	//query all the contact in a single query
	List<Contact> cont = new List<Contact>();
	
	cont = [select id, Major_Market_Roadshows_Green__c from Contact where id in :liContIds and FSIC_Approved__c != NULL];
	
	for ( Contact conts : cont)
	{
		conts.Major_Market_Roadshows_Green__c = 'Y' ; 
	}

	if(cont.size() > 0)
	
	update cont;
	}
	
	global void finish(Database.BatchableContext BC){} 	
}

 Not really sure what I am missing.

 

Thank you in advance for the help.

 

Ok.....just need a bit of help to understand what I am doing wrong.

 

I have all of the attributes I need to display this page in the left subtab sidebar of the service cloud console....I think. I am not sure why it is not showing anything. I have records that should be aggregating and they are not. Can someone tell me why?

 

Controller:

public class NS_ConsoleCaseChartController {
	
	public String strContactID;
	public String strCaseID;
	
	public NS_ConsoleCaseChartController(ApexPages.StandardController stdController){
        strCaseID = ApexPages.currentPage().getParameters().get('Id');
	}
	
	public List<ChartDataItem> getChartData()
	{
		List<ChartDataItem> items = new List<ChartDataItem>();
		
		strContactId = string.valueOf(Case.ContactId);
		
		AggregateResult[] groupedTasks = [SELECT Type, Count(Id) ID FROM Task WHERE WhoId =: strContactID GROUP BY Type];
		
		for (AggregateResult ar : groupedTasks)
		{
			items.add(new ChartDataItem( String.valueOf(ar.get('Type')), Integer.valueOf(ar.get('ID'))));
		}
		
		System.debug(items);
		return items;
	}
	
	public class ChartDataItem
	{
		public String Label {get; set;}
		public Integer Value {get; set;}
		
		public ChartDataItem(String Label, Integer Value)
		{	
			this.Label = Label;
			this.Value = Value;
		}
	}
}

 VF Page:

<apex:page standardController="Case" extensions="NS_ConsoleCaseChartController">
<apex:includeScript value="/soap/ajax/26.0/connection.js"/>
<apex:includeScript value="/support/console/26.0/integration.js"/>
<script type="text/javascript">  
  function openNewSubtab() {
      sforce.console.getFocusedPrimaryTabId(Id);
  	} 
</script>  
	<apex:chart height="195" width="250" data="{!chartData}">
        <apex:pieSeries dataField="Value" labelField="Label"/>
        <apex:legend position="bottom"/>
    </apex:chart>
</apex:page>

 I am really trying to figure out what I am missing here. I am new to developing in the Service Cloud Console.

 

 

All I am writing an Inbound Message Class to handle XML in the body of the e-mail. I am struggling with one error and I am not sure how to resolve it. Any assistance would be appreciated. Below is my class. My Error is on line 95. It is Method Does Not Exist or Incorrect Signature: getDecodedString(System.XMLStreamReader) I understand that it is missing an element before 'reader', btu honestly I am not sure what it should be.

 

/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class Email_CustomerRecord implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
		
		List<Account> act1;
		try
		{
			String messageBody = '';
			String action = '';
			String cust_num = '';
			String name = '';
			String cust_seq = '';
			String addr1 = '';
			String addr2 = '';
			String addr3 = '';
			String addr4 = '';
			String city = '';
			String CusCounty = '';
			String state = '';
			String country = '';
			String zip = '';
			
			messageBody = email.plainTextBody;
			messageBody = messageBody.trim();
			
			messageBody = messageBody.substring(messageBody.indexof('<?xml version="1.0" encoding="UTF-8"?>'),messageBody.indexOf('</CustomerRecord>')+12);
			
			Action = readXMLelement(messageBody,'action');
			
			String cn = readXMLelement(messageBody,'cust_num');
			List<Account> actl = [SELECT Id, Customer_Number__c, Name, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry
									  FROM Account 
									  WHERE Customer_Number__c =: cn
									  ];
			
			if(Action == 'add')
			{
				Account act = new Account();
				
				act.Customer_Number__c = readXMLelement(messageBody,'cust_num');
				act.Name = readXMLelement(messageBody,'name');
				act.BillingStreet = readXMLelement(messageBody,'addr1') + readXMLelement(messageBody,'addr2') + readXMLelement(messageBody,'addr3') + readXMLelement(messageBody,'addr4');
				act.BillingCity  = readXMLelement(messageBody,'city');
				act.BillingState  = readXMLelement(messageBody,'state');
				act.BillingPostalCode  = readXMLelement(messageBody,'zip');
				act.BillingCountry  = readXMLelement(messageBody,'country');
				
				insert act;
			}
			if(Action == 'modify')
			{
				for(Account actList : act1)
				{
					actList.Name = readXMLelement(messageBody,'name');
					actList.BillingStreet = readXMLelement(messageBody,'addr1') + readXMLelement(messageBody,'addr2') + readXMLelement(messageBody,'addr3') + readXMLelement(messageBody,'addr4');
					actList.BillingCity  = readXMLelement(messageBody,'city');
					actList.BillingState  = readXMLelement(messageBody,'state');
					actList.BillingPostalCode  = readXMLelement(messageBody,'zip');
					actList.BillingCountry  = readXMLelement(messageBody,'country');
				}
				
				update act1;					
			}
			if(Action == 'delete')
			{
				delete act1;
			}
		}
		catch(exception e)
		{
			
		}
		
        return result;
    }
    public static String readXMLelement(String xml, String element)
    {
        String elementValue = 'NOT FOUND'; 
        
        try
        {
	        Xmlstreamreader reader = new Xmlstreamreader(xml);
	        while (reader.hasNext()) 
	        {
	            if (reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == element)
	            {
	                System.debug('Found SID');
	                reader.next();
	                elementValue = getDecodedString(reader); <---Error Method Does Not Exist or Incorrect Signature: getDecodedString(System.XMLStreamReader)
	            }         
	            reader.next();
	        }
	        return elementValue;
        }
        catch(exception e)
        {
			String err;
			err = e.getMessage();
			return err;
        }
    }
}

 Thank you for your assistance.

All I am currently displaying a VF page in landscape. I understand the attributes and the display for this is correct. The issue I am having is that when I render the PDF, it will not display in landscape, even when usine the  size: landscape;           attribute. Is anyone aware of a different way of rendering this?

 

Thank you for any assistance.

All -

 

I am creating an email messaging service and I understand how to do it with text in the body, however this specific e-mail is being sent with XML format in the body. Does anyone know the best way to indicate the next line for this type of format? I understand the code for next line etc...but this one is new to me. Any assistance would help.

 

 

Not really sure how to write this class. I cannot seem to get any coverage, and I am stumped as to why.

 

Here is my class:

public with sharing class MyChartController {
	
	public String strCase;
	
	public MyChartController(ApexPages.StandardController stdController){
		strCase = ApexPages.currentPage().getParameters().get('Id'); 
	}
   
	public List<AggregateResult> getDatabyType(){
   		Case c = [Select id, ContactId From Case where id =: strCase LIMIT 1];
   
   		List<AggregateResult> result = [Select COUNT(Id) tskCNT, Type FROM Task WHERE WhoId =: c.ContactId GROUP BY Type];
    	return result;      
	}
}

 And here is the Test Class that has no coverage results:

@isTest
private class MyChartController_Test {

    static testMethod void MyChartController_Test() {
    	
    	PageReference pageRef1 = Page.MyChart;
    	pageRef1.getParameters().get('Id');
    	Test.setCurrentPage(pageRef1);
    	
    	Account act1 = new Account();
    	act1.LastName = 'Test';
    	act1.RecordTypeId = '012i00000006R7z';
    	
    	insert act1;
    	
    	Contact ct1 = new Contact();
    	ct1.AccountId = act1.ParentId;
    	ct1.FirstName = 'John';
    	ct1.LastName = 'Test';
    	
    	insert ct1;
    	
    	Task tsk1 = new Task();
    	tsk1.Subject = 'Other';
    	tsk1.Priority = 'High';
    	tsk1.OwnerId = '005i0000000t0F5';
    	tsk1.Type = 'Follow';
    	tsk1.Status = 'Completed';
    	tsk1.WhoId = ct1.Id;
    	
    	insert tsk1;
    	
    	Case cs1 = new Case();
    	cs1.Origin = 'Web';
    	cs1.ContactId = ct1.Id;
    	cs1.Status = 'Closed';
    	
    	insert cs1;
    	
    	ApexPages.currentPage().getParameters().put('retURL','/'+cs1.id);
    	
    	MyChartController(new ApexPages.StandardController(cs1));
    }
}

 Any assistance and guidance would be greatly appreciated.

Hi All -

 

I am getting the following error for a rollup trigger that I have written and I am not sure how to solve it.

 

Error is on line 45 of the code: 

RollUpUnitAmounts - Unable to update Engagement__c.
Exception encountered Invalid field Id for AggregateResult

The code is:

trigger RollUpUnitAmounts on Product__c (after insert, after update, after undelete, after delete) 
{

	Product__c[] products;

    if (trigger.isDelete)
    {
        products = Trigger.old;
    }
    else
    {
        products = Trigger.new;
    }
    
    Set<Id> set_EngageIds = new Set<Id>();
     
    for (Product__c p:products)
    {
        if (p.Engagement__c != null)
        {
        	set_EngageIds.add(p.Engagement__c);
        }
    }
	
	List<Engagement__c> engagList;
	Map<ID, Engagement__c> engagMap;
	
	try{
	Map<Id,Engagement__c> engtuMap = new Map<Id,Engagement__c>();
	Map<Id,Engagement__c> toBeUpdated = new Map<Id,Engagement__c>();
	String engagementId = '';
	
	for (Engagement__c e : (engagList = [SELECT id,Total_Units__c from Engagement__c where id IN:set_EngageIds]))
        {
        	engagMap = new Map<ID, Engagement__c>(engagList);
        	e.Total_Units__c = 0;
        	engagementId = e.Id;
        	
        	List<AggregateResult> aresults = [select SUM(Units__c)totalUnit from Product__c where id in :set_EngageIds];
        	
        	if (aresults!=null && aresults.size()>0)
        	{
        		for (AggregateResult ar : aresults)
        		{
        			Engagement__c parentEngagement = engagMap.get(String.valueOf(ar.get('Id')));
        			if (parentEngagement!=null) 
                        {
                        	if (ar.get('parentEngagement') != null) 
                                    {
                                        parentEngagement.Total_Units__c = Double.valueOf(String.valueOf(ar.get('parentEngagement'))).intValue();
                                    }
                            
                            break;
                        }
                        
                        engtuMap.put(parentEngagement.Id,parentEngagement);
        		}
        	}
        	if(engtuMap.values().size()>0)
            {
                toBeUpdated.putAll(engtuMap);
            }
        }
        if(toBeUpdated.size()>0)
        {
            update toBeUpdated.values();
        }
        else
        {
            if(engagMap.size()>0)
            {
                update engagMap.values();
            }
        }
        }
	    catch (Exception e) 
    	{
        	System.debug('\n\n>> RollUpUnitAmounts - Unable to update Engagement__c.\nException encountered ' + e.getMessage());
    	}
	}

 Thank you for any assistance you can provide.

RollUpUnitAmounts - Unable to update Engagement__c.
Exception encountered Invalid field Id for AggregateResult

All -

 

So I think I just need direction on a place to start. I have been using google Charts and Visualizations to display complex scatter charts and line graphs. They way I have accomplished this is through the use of long text fields that contain up to 4K plot point in the X and 4000 in the Y field. This has allowed me to do some really great displays.

 

Now my user is asking me if I can layer my line graphs. Each line graph has it's own X and Y. To be clear, they rarely share a location on a graph (ie...X1 != X2 or Y1 != Y2). I have read and viewed many layered sales graphs that use the same year or month, but I do not have that commonality in mine. 

 

Is there a way to do a layered line graph with up to 6 lines where the only constant is my Max and Min? Can someone point me in the right direction? I would like to use VF Charts if at all possible.

 

Thank you in advance for any assistance you can provide.

 

JP

All -

 

I have created an integration that creates over 2000 records. The reason that it is so high is that I am parsing 2 very large fields on the C# side of the integration. I desperately need to reduce my API calls so the only solution is for me to parse the data in Salesforce. I do not even know where to begin. The data would come in in two very large text fields. Each value in each field has exactly 8 characters after the decimal. I would need to parse and translate these values in pair values that create multiple recors in SFDC.

 

Can someone point me in the correct direction?

 

TechEd

Ok....I have been on here with one error or another trying to write a webservice that is consumed by C#. I thought I had it, but continue to run into issues. Below is the code that I have written. I am struggling with how to make the objects relate as well as test code coverage. On teh C# side, I have it. Can someone please assist me? Here is the code below that I have been writing. The Patient Data is the Parent to the Trial Session. I know I am missing something here and could really use some guidance.

global
class wsLoad_NDD_Data {
	
	webservice static Patient_Data__c LoadPatientData(String strPatientId, String strFirstName, String strLastName, String strIsBioCal, String strEthnicity, String strAsthma, String strGender, Date dtmDateOfBirth, String strCOPD, Decimal numHeight, Decimal numWeight, String strsite)
	{
		Patient_Data__c insertPatientData = null;
		
		insertPatientData = new Patient_Data__c();
		
		insertPatientData.Patient_ID__c = strPatientId;
		insertPatientData.First_Name__c = strFirstName;
		insertPatientData.Last_Name__c = strLastName;
		insertPatientData.IsBioCal_Int__c = strIsBioCal;
		insertPatientData.Ethnicity__c = strEthnicity;
		insertPatientData.Asthma__c = strAsthma;
		insertPatientData.Gender__c = strGender;
		insertPatientData.Date_of_Birth__c = dtmDateOfBirth;
		insertPatientData.COPD__c = strCOPD;
		insertPatientData.Height__c = numHeight;
		insertPatientData.Weight__c = numWeight;
		insertPatientData.Site__c = strsite;
		
		insert insertPatientData;
		
		return insertPatientData;
		}
		
	webservice static Trial_Session__c LoadTrialSession(String strOrderID, Date dtmTestDate, String strTypeofTest, String strReviewerName, String strReviewerComments, Date dtmDateofBirth, Decimal numHeight, Decimal numWeight, String strGender, String strEthnicity, String strAsthma, String strCOPD, String strSmoker, Date dtmDateReviewed, Decimal numLungAge, String strQualityGrade, String strQualityGradeOriginal, String strSoftwareVersion)
	{
		Trial_Session__c insertTrialSession = null;
		
		insertTrialSession = new Trial_Session__c();
		
		insertTrialSession.Patient_Data__c = ;
		insertTrialSession.External_ID__c = strOrderID;
		insertTrialSession.Test_Date__c = dtmTestDate;
		insertTrialSession.Type_of_Test__c = strTypeofTest;
		insertTrialSession.Reviewer_Name__c = strReviewerName;
		insertTrialSession.Reviewer_Comments__c = strReviewerComments;
		insertTrialSession.Date_of_Birth__c = dtmDateofBirth;
		insertTrialSession.Height__c = numHeight;
		insertTrialSession.Weight__c = numWeight;
		insertTrialSession.Gender__c = strGender;
		insertTrialSession.Ethnicity__c = strEthnicity;
		insertTrialSession.Asthma__c = strAsthma;
		insertTrialSession.COPD__c = strCOPD;
		insertTrialSession.Smoker__c = strSmoker;
		insertTrialSession.Date_Reviewed__c = dtmDateReviewed;
		insertTrialSession.Lung_Age__c = numLungAge;
		insertTrialSession.Quality_Grade__c = strQualityGrade;
		insertTrialSession.Quality_Grade_Original__c = strQualityGradeOriginal;
		insertTrialSession.Software_Version__c = strSoftwareVersion;
		
		insert insertTrialSession;
		
		return insertTrialSession;
	}
}

 I am also really struggling with the test class. In all of the research I have done I have seen two possible ways to handle this and very little guidance on how to relate objects.

 

Thank you for the help provided. I know this can be done, I just need a bit of the path shown to me.

 

JP

All I am getting the above Error when trying to insert records from an integration.

 

Here iso the code it is erroring on: IT is erroring on the live that begins: List<Patient_Data__c> objPatient

global class wsLoad_NDD_Data {

Value, Trial, Trial Data, Result Parameters)
	global class PatientData{
		WebService String strPatientId;
		WebService String strFirstName;
		WebService String strLastName;
		WebService String strIsBioCal;
		WebService String strEthnicity;
		WebService String strAsthma;
		WebService String strGender;
		WebService Date dtmDateOfBirth;
		WebService String strCOPD;
		WebService Decimal numHeight;
		WebService Decimal numWeight;
		WebService String strSite;
		WebService String strSmoker;
		}
	
	webservice static Patient_Data__c LoadPatientData(PatientData PDInfo)
    {
		 Patient_Data__c insertPatientData = null;
         // Look for the Patient_Data_ID__c being passed in.
         List<Patient_Data__c> objPatient = [SELECT Patient_ID__c FROM Patient_Data__c WHERE Patient_ID__c = :PDInfo.strPatientId];
         
         if(objPatient.size() > 0)
        {
        	//Existing Patient Check
        	
        	List<Patient_Data__c> updatePatientData = [SELECT First_Name__c, Last_Name__c, IsBioCal__c, Ethnicity__c, Asthma__c, Gender__c, Date_of_Birth__c, COPD__c, Height__c, Weight__c  FROM Patient_Data__c
            WHERE Patient_ID__c = :PDInfo.strPatientId];
            for (Patient_Data__c pd : updatePatientData)
            {	
              
            pd.First_Name__c = PDInfo.strFirstName;
            pd.Last_Name__c = PDInfo.strLastName;
            pd.IsBioCal_Int__c = PDInfo.strIsBioCal;
            pd.Ethnicity__c = PDInfo.strEthnicity;
            pd.Asthma__c = PDInfo.strAsthma;
            pd.Gender__c = PDInfo.strGender;
            pd.Date_of_Birth__c = PDInfo.dtmDateOfBirth;
            pd.COPD__c = PDInfo.strCOPD;
            pd.Height__c = PDInfo.numHeight;
            pd.Weight__c = PDInfo.numWeight; 
            pd.Site__c = PDInfo.strsite; 
            }
        update updatePatientData;
        }
        else
        {
            // Get list of Patients.
            // New Patient.
            insertPatientData = new Patient_Data__c();
            
            insertPatientData.Patient_ID__c = PDInfo.strPatientId;
            insertPatientData.First_Name__c = PDInfo.strFirstName;
            insertPatientData.Last_Name__c = PDInfo.strLastName;
            insertPatientData.IsBioCal_Int__c = PDInfo.strIsBioCal;
            insertPatientData.Ethnicity__c = PDInfo.strEthnicity;
            insertPatientData.Asthma__c = PDInfo.strAsthma;
            insertPatientData.Gender__c = PDInfo.strGender;
            insertPatientData.Date_of_Birth__c = PDInfo.dtmDateOfBirth;
            insertPatientData.COPD__c = PDInfo.strCOPD;
            insertPatientData.Height__c = PDInfo.numHeight;
            insertPatientData.Weight__c = PDInfo.numWeight; 
            insertPatientData.Site__c = PDInfo.strsite;
        
            insert insertPatientData;     
       }
	   return insertPatientData;
    }

Please help.

 

TechEd

I have a flag in my Aura:if that allows me to add columns to my interface. I am able to access the controller, however, it does not appear to be updating the flag.

Component Code:
<aura:if isTrue="{!(not(v.showYear4))}">
                    	<lightning:buttonIcon name="4" iconName="utility:add" title="Add Year 4" onclick="{!c.addColumn}" />
                    </aura:if>
                </th>
                <aura:if isTrue="{!v.showYear4}">
                    <th scope="col">
                        <span class="slds-truncate" title="YR4">Year 4</span>
                    </th>
                </aura:if>
Controller Code:
addColumn : function(component, event, helper){
    	
        console.log("made it here");
        var currentTarget = event.currentTarget;
        var currentYear = currentTarget.getAttribute("name");
        component.set("v.showYear"+currentYear,true);
        console.log("v.showYear"+currentYear);
        
    }

Any help wouldd be appreciated. The code is not displaying the second console.log statement but is displaying "made it here"


 
As I need to filter out specific activities from a list, I am attempting to create the ActivityHistory and Open Activity component for a Lightning Page.

I understand how to display lists when they are different objects, however, when I am querying form the same object I am struggling with determining how to display each list where I want.

APEX Controller:
public with sharing class CH_Activity_Viewer_Controller {
@AuraEnabled
public static List<WorkOrder> getOpenAvtivities(Id recordId)
{
    System.debug(recordId);
    return [SELECT Id, (SELECT Id, Subject, Who.Name, StartDateTime, DurationInMinutes FROM OpenActivities) FROM WorkOrder WHERE Id = :recordId];
}

@AuraEnabled
public static List<WorkOrder> getActivityHistory(Id recordId)
{
    System.debug(recordId);
    return [SELECT Id, (SELECT Id, Subject, Who.Name, StartDateTime, DurationInMinutes FROM ActivityHistories) FROM WorkOrder WHERE Id = :recordId];
}
}

Lightning Controller
({
loadInterface : function(component, event, helper)
{
    $( function()
    {
        $( "#accordion" ).accordion();
    });
},

doInit : function(component, event, helper)
{
    var action1 = component.get("c.getOpenAvtivities");
    var action2 = component.get("c.getActivityHistory");
    action1.setParams({
        "recordId" : component.get("v.recordId")
    });
    action1.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            //update all the action1 attributes in the component.
            component.set("v.action1",response.getReturnValue());               
        }
        else if (state === "ERROR") {
            var errors = response.getError();
            if (errors) {
                if (errors[0] && errors[0].message) {
                    console.log("Error message: " + 
                             errors[0].message);
                }
            } else {
                console.log("Unknown error");
            }
        }
    });
    action2.setParams({
        "recordId" : component.get("v.recordId")
    });
    action2.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            //update all the action2 attributes in the component.
            component.set("v.action2",response.getReturnValue());               
        }
        else if (state === "ERROR") {
            var errors = response.getError();
            if (errors) {
                if (errors[0] && errors[0].message) {
                    console.log("Error message: " + 
                             errors[0].message);
                }
            } else {
                console.log("Unknown error");
            }
        }
    });

    $A.enqueueAction(action1);
    $A.enqueueAction(action2);
}  
})

Component
<aura:component controller="CH_Activity_Viewer_Controller" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
<ltng:require scripts="/resource/ActivityViewer/ActivityViewer/jquery-3.2.1.min.js,/resource/ActivityViewer/ActivityViewer/jquery-ui.js" afterScriptsLoaded="{!c.loadInterface}"/>
<ltng:require styles="/resource/ActivityViewer/ActivityViewer/jquery-ui.css"/>
<aura:attribute name="action1" type="WorkOrder[]" />
<aura:attribute name="action2" type="WorkOrder[]" />
<aura:attribute name="recordId" type="Id" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />



<div id="accordion">
    <h3>Open Activities</h3>
    <div>
        <aura:iteration var="wo1" items="{!v.action1}" >
            <aura:iteration var="act1" items="{!wo1.OpenActivities}" >
            <p><b>{!act1.Subject}</b></p>
            <p>{!act1.Who.Name}</p>
            <p>{!act1.StartDateTime}</p>
            <p>{!act1.DurationInMinutes} MIN</p>
            </aura:iteration>
        </aura:iteration>
    </div>
    <h3>Activity History</h3>
    <div>
        <aura:iteration var="wo2" items="{!v.action2}" >
            <aura:iteration var="act2" items="{!wo2.OpenActivities}" >
            <p><b>{!act2.Subject}</b></p>
            <p>{!act2.Who.Name}</p>
            <p>{!act2.StartDateTime}</p>
            <p>{!act2.DurationInMinutes} MIN</p>
            </aura:iteration>
        </aura:iteration>
    </div>
</div>

Any Help is greatly appreciated.​

So here is the business case:

 

If an opportunity is ia a mature stage, prevent the deletion of all contact roles.

 

Here is the code I created to accomplish this goal. I need to stop the deletion from occuring on teh COntact Rols, but cannot write triggers on contact role. The below controller is associated to a VF Page to get it to run taht is hiddien in the standard layout.

 

public with sharing class CROppHelper {
	
	public Opportunity opp;
	public CROppHelper( ApexPages.StandardController stdController ) {
        opp = ( Opportunity )stdController.getRecord();        
    }
    public void rollupOppContactRole(){
        CROppHelper.rollupOppContactRoleFuture(opp.Id);
    }
    @future public static void rollupOppContactRoleFuture( Id oppId ) 
    {
    	Integer priCnt;
        OpportunityContactRole[] oppRoleList = [SELECT ContactId, IsPrimary FROM OpportunityContactRole
                                         WHERE OpportunityId = :oppId];
        Opportunity opp = [Select ID from Opportunity where Id =: oppId];
        If(oppRoleList.size() > 0)
        {
        	for( OpportunityContactRole oppRole : oppRoleList ) 
        	{
        		if(oppRole.IsPrimary == TRUE)
        		{
        			priCnt = 1;
        		}
        	
        		if(priCnt == 1)
        		{
        			opp.addError('Opportinuty must have a Primary Contact Role in order to be in this stage.');
        		}
        	}
        }
        update opp;
    }
}

VF Page

<apex:page standardController="Opportunity" extensions="CROppHelper" action="{!rollupOppContactRole}"/>

 

 

 When a CR is deleted the code is being triggered to run, but it is not preventing the deletion, nor is it displaying the error on the opportunity. Can I have some assistance please?

So I cannot seem to figure this one out. I do not use maps all that often and I am having a hard time determining how to update a value from it.

 

I am trying to update the inventory by subtracting the value from the map. Pleas see the code below:

trigger PO_Request_Update_Inv_Transit on PO_Request__c (after update) {

	PO_Request__c[] porequest;
	
	Set<Id> poSet = new Set<Id>();
	Set<Id> podetailSet = new Set<Id>();
	Set<Id> inventorySet = new Set<Id>();
	Map<String, Decimal> popartMap = new Map<String, Decimal>();
	List<Inventory__c> inventoryList = new List<Inventory__c>();
	List<PO_Request_Detail__c> porequestdetailList = new List<PO_Request_Detail__c>();
	
	for(PO_Request__c po:porequest)
	{
		poSet.add(po.Id);
		Decimal invQty = 0;
		
		If(po.PO_Req_Status__c == 'Approved')
		{
			porequestdetailList = [Select Id, PO_Request__c, Part_Num__c, Qty__c from PO_Request_Detail__c where PO_Request__c IN : poSet];
			
			for(PO_Request_Detail__c prd:porequestdetailList)
			{
				popartMap.put(prd.Part_Num__r.Id, prd.Qty__c);
				podetailSet.add(prd.Part_Num__c);
			}
			
			inventoryList = [Select Part_Num__r.Id, Qty__c from Inventory__c where Part_Num__c IN :podetailSet];
			
			for(Integer i = 0; i < inventoryList.size(); i++)
			{
				if(popartMap.containsKey(inventoryList[i].Part_Num__r.Id))
				{
					inventoryList[i].Qty__c = inventoryList[i].Qty__c - 
				}
				update inventoryList;
			}
		}
	}
}

 My main problem is how to get the mapped value and use it in my calculation to update.

 

inventoryList[i].Qty__c = inventoryList[i].Qty__c - ???

 

Thank you for your help.

Below is the Batch Job I have created. I am a litle fuzzy as to how to implement this in the shceduler. Can someone assist?

 

global class UpdateContactFlags implements Schedulable, Database.Batchable<sObject>{
	public string query = 'SELECT Id, Contact.Id, Campaign.Fund_s__c, Campaign.Listing_Tactic__c, Status from CampaignMember';
		
	global Database.Querylocator start(Database.BatchableContext BC)
	{
		
		return Database.getQueryLocator(query);
	}
	
	global void execute(SchedulableContext SC)
	{
		UpdateContactFlags ucfg = new UpdateContactFlags();
		database.executebatch(ucfg, 100);
	}
	
	global void execute(Database.BatchableContext BC, List<sObject> scope)
	{
	Set<id> liContIds = new Set<id>();

	for(sObject s : scope){
		CampaignMember cm = (CampaignMember)s;

		if(cm.Campaign.Fund_s__c == 'FSIC' && cm.Campaign.IsActive == TRUE && cm.Campaign.Listing_Tactic__c == 'Major Market Roadshow')
			liContIds.add(cm.Contact.Id);
		}

	//query all the contact in a single query
	List<Contact> cont = new List<Contact>();
	
	cont = [select id, Major_Market_Roadshows_Green__c from Contact where id in :liContIds and FSIC_Approved__c != NULL];
	
	for ( Contact conts : cont)
	{
		conts.Major_Market_Roadshows_Green__c = 'Y' ; 
	}

	if(cont.size() > 0)
	
	update cont;
	}
	
	global void finish(Database.BatchableContext BC){} 	
}

 Not really sure what I am missing.

 

Thank you in advance for the help.

 

Ok.....just need a bit of help to understand what I am doing wrong.

 

I have all of the attributes I need to display this page in the left subtab sidebar of the service cloud console....I think. I am not sure why it is not showing anything. I have records that should be aggregating and they are not. Can someone tell me why?

 

Controller:

public class NS_ConsoleCaseChartController {
	
	public String strContactID;
	public String strCaseID;
	
	public NS_ConsoleCaseChartController(ApexPages.StandardController stdController){
        strCaseID = ApexPages.currentPage().getParameters().get('Id');
	}
	
	public List<ChartDataItem> getChartData()
	{
		List<ChartDataItem> items = new List<ChartDataItem>();
		
		strContactId = string.valueOf(Case.ContactId);
		
		AggregateResult[] groupedTasks = [SELECT Type, Count(Id) ID FROM Task WHERE WhoId =: strContactID GROUP BY Type];
		
		for (AggregateResult ar : groupedTasks)
		{
			items.add(new ChartDataItem( String.valueOf(ar.get('Type')), Integer.valueOf(ar.get('ID'))));
		}
		
		System.debug(items);
		return items;
	}
	
	public class ChartDataItem
	{
		public String Label {get; set;}
		public Integer Value {get; set;}
		
		public ChartDataItem(String Label, Integer Value)
		{	
			this.Label = Label;
			this.Value = Value;
		}
	}
}

 VF Page:

<apex:page standardController="Case" extensions="NS_ConsoleCaseChartController">
<apex:includeScript value="/soap/ajax/26.0/connection.js"/>
<apex:includeScript value="/support/console/26.0/integration.js"/>
<script type="text/javascript">  
  function openNewSubtab() {
      sforce.console.getFocusedPrimaryTabId(Id);
  	} 
</script>  
	<apex:chart height="195" width="250" data="{!chartData}">
        <apex:pieSeries dataField="Value" labelField="Label"/>
        <apex:legend position="bottom"/>
    </apex:chart>
</apex:page>

 I am really trying to figure out what I am missing here. I am new to developing in the Service Cloud Console.

 

 

All I am writing an Inbound Message Class to handle XML in the body of the e-mail. I am struggling with one error and I am not sure how to resolve it. Any assistance would be appreciated. Below is my class. My Error is on line 95. It is Method Does Not Exist or Incorrect Signature: getDecodedString(System.XMLStreamReader) I understand that it is missing an element before 'reader', btu honestly I am not sure what it should be.

 

/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class Email_CustomerRecord implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
		
		List<Account> act1;
		try
		{
			String messageBody = '';
			String action = '';
			String cust_num = '';
			String name = '';
			String cust_seq = '';
			String addr1 = '';
			String addr2 = '';
			String addr3 = '';
			String addr4 = '';
			String city = '';
			String CusCounty = '';
			String state = '';
			String country = '';
			String zip = '';
			
			messageBody = email.plainTextBody;
			messageBody = messageBody.trim();
			
			messageBody = messageBody.substring(messageBody.indexof('<?xml version="1.0" encoding="UTF-8"?>'),messageBody.indexOf('</CustomerRecord>')+12);
			
			Action = readXMLelement(messageBody,'action');
			
			String cn = readXMLelement(messageBody,'cust_num');
			List<Account> actl = [SELECT Id, Customer_Number__c, Name, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry
									  FROM Account 
									  WHERE Customer_Number__c =: cn
									  ];
			
			if(Action == 'add')
			{
				Account act = new Account();
				
				act.Customer_Number__c = readXMLelement(messageBody,'cust_num');
				act.Name = readXMLelement(messageBody,'name');
				act.BillingStreet = readXMLelement(messageBody,'addr1') + readXMLelement(messageBody,'addr2') + readXMLelement(messageBody,'addr3') + readXMLelement(messageBody,'addr4');
				act.BillingCity  = readXMLelement(messageBody,'city');
				act.BillingState  = readXMLelement(messageBody,'state');
				act.BillingPostalCode  = readXMLelement(messageBody,'zip');
				act.BillingCountry  = readXMLelement(messageBody,'country');
				
				insert act;
			}
			if(Action == 'modify')
			{
				for(Account actList : act1)
				{
					actList.Name = readXMLelement(messageBody,'name');
					actList.BillingStreet = readXMLelement(messageBody,'addr1') + readXMLelement(messageBody,'addr2') + readXMLelement(messageBody,'addr3') + readXMLelement(messageBody,'addr4');
					actList.BillingCity  = readXMLelement(messageBody,'city');
					actList.BillingState  = readXMLelement(messageBody,'state');
					actList.BillingPostalCode  = readXMLelement(messageBody,'zip');
					actList.BillingCountry  = readXMLelement(messageBody,'country');
				}
				
				update act1;					
			}
			if(Action == 'delete')
			{
				delete act1;
			}
		}
		catch(exception e)
		{
			
		}
		
        return result;
    }
    public static String readXMLelement(String xml, String element)
    {
        String elementValue = 'NOT FOUND'; 
        
        try
        {
	        Xmlstreamreader reader = new Xmlstreamreader(xml);
	        while (reader.hasNext()) 
	        {
	            if (reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == element)
	            {
	                System.debug('Found SID');
	                reader.next();
	                elementValue = getDecodedString(reader); <---Error Method Does Not Exist or Incorrect Signature: getDecodedString(System.XMLStreamReader)
	            }         
	            reader.next();
	        }
	        return elementValue;
        }
        catch(exception e)
        {
			String err;
			err = e.getMessage();
			return err;
        }
    }
}

 Thank you for your assistance.

All -

 

I am creating an email messaging service and I understand how to do it with text in the body, however this specific e-mail is being sent with XML format in the body. Does anyone know the best way to indicate the next line for this type of format? I understand the code for next line etc...but this one is new to me. Any assistance would help.

 

 

Not really sure how to write this class. I cannot seem to get any coverage, and I am stumped as to why.

 

Here is my class:

public with sharing class MyChartController {
	
	public String strCase;
	
	public MyChartController(ApexPages.StandardController stdController){
		strCase = ApexPages.currentPage().getParameters().get('Id'); 
	}
   
	public List<AggregateResult> getDatabyType(){
   		Case c = [Select id, ContactId From Case where id =: strCase LIMIT 1];
   
   		List<AggregateResult> result = [Select COUNT(Id) tskCNT, Type FROM Task WHERE WhoId =: c.ContactId GROUP BY Type];
    	return result;      
	}
}

 And here is the Test Class that has no coverage results:

@isTest
private class MyChartController_Test {

    static testMethod void MyChartController_Test() {
    	
    	PageReference pageRef1 = Page.MyChart;
    	pageRef1.getParameters().get('Id');
    	Test.setCurrentPage(pageRef1);
    	
    	Account act1 = new Account();
    	act1.LastName = 'Test';
    	act1.RecordTypeId = '012i00000006R7z';
    	
    	insert act1;
    	
    	Contact ct1 = new Contact();
    	ct1.AccountId = act1.ParentId;
    	ct1.FirstName = 'John';
    	ct1.LastName = 'Test';
    	
    	insert ct1;
    	
    	Task tsk1 = new Task();
    	tsk1.Subject = 'Other';
    	tsk1.Priority = 'High';
    	tsk1.OwnerId = '005i0000000t0F5';
    	tsk1.Type = 'Follow';
    	tsk1.Status = 'Completed';
    	tsk1.WhoId = ct1.Id;
    	
    	insert tsk1;
    	
    	Case cs1 = new Case();
    	cs1.Origin = 'Web';
    	cs1.ContactId = ct1.Id;
    	cs1.Status = 'Closed';
    	
    	insert cs1;
    	
    	ApexPages.currentPage().getParameters().put('retURL','/'+cs1.id);
    	
    	MyChartController(new ApexPages.StandardController(cs1));
    }
}

 Any assistance and guidance would be greatly appreciated.

Hi All -

 

I am getting the following error for a rollup trigger that I have written and I am not sure how to solve it.

 

Error is on line 45 of the code: 

RollUpUnitAmounts - Unable to update Engagement__c.
Exception encountered Invalid field Id for AggregateResult

The code is:

trigger RollUpUnitAmounts on Product__c (after insert, after update, after undelete, after delete) 
{

	Product__c[] products;

    if (trigger.isDelete)
    {
        products = Trigger.old;
    }
    else
    {
        products = Trigger.new;
    }
    
    Set<Id> set_EngageIds = new Set<Id>();
     
    for (Product__c p:products)
    {
        if (p.Engagement__c != null)
        {
        	set_EngageIds.add(p.Engagement__c);
        }
    }
	
	List<Engagement__c> engagList;
	Map<ID, Engagement__c> engagMap;
	
	try{
	Map<Id,Engagement__c> engtuMap = new Map<Id,Engagement__c>();
	Map<Id,Engagement__c> toBeUpdated = new Map<Id,Engagement__c>();
	String engagementId = '';
	
	for (Engagement__c e : (engagList = [SELECT id,Total_Units__c from Engagement__c where id IN:set_EngageIds]))
        {
        	engagMap = new Map<ID, Engagement__c>(engagList);
        	e.Total_Units__c = 0;
        	engagementId = e.Id;
        	
        	List<AggregateResult> aresults = [select SUM(Units__c)totalUnit from Product__c where id in :set_EngageIds];
        	
        	if (aresults!=null && aresults.size()>0)
        	{
        		for (AggregateResult ar : aresults)
        		{
        			Engagement__c parentEngagement = engagMap.get(String.valueOf(ar.get('Id')));
        			if (parentEngagement!=null) 
                        {
                        	if (ar.get('parentEngagement') != null) 
                                    {
                                        parentEngagement.Total_Units__c = Double.valueOf(String.valueOf(ar.get('parentEngagement'))).intValue();
                                    }
                            
                            break;
                        }
                        
                        engtuMap.put(parentEngagement.Id,parentEngagement);
        		}
        	}
        	if(engtuMap.values().size()>0)
            {
                toBeUpdated.putAll(engtuMap);
            }
        }
        if(toBeUpdated.size()>0)
        {
            update toBeUpdated.values();
        }
        else
        {
            if(engagMap.size()>0)
            {
                update engagMap.values();
            }
        }
        }
	    catch (Exception e) 
    	{
        	System.debug('\n\n>> RollUpUnitAmounts - Unable to update Engagement__c.\nException encountered ' + e.getMessage());
    	}
	}

 Thank you for any assistance you can provide.

RollUpUnitAmounts - Unable to update Engagement__c.
Exception encountered Invalid field Id for AggregateResult

All -

 

So I think I just need direction on a place to start. I have been using google Charts and Visualizations to display complex scatter charts and line graphs. They way I have accomplished this is through the use of long text fields that contain up to 4K plot point in the X and 4000 in the Y field. This has allowed me to do some really great displays.

 

Now my user is asking me if I can layer my line graphs. Each line graph has it's own X and Y. To be clear, they rarely share a location on a graph (ie...X1 != X2 or Y1 != Y2). I have read and viewed many layered sales graphs that use the same year or month, but I do not have that commonality in mine. 

 

Is there a way to do a layered line graph with up to 6 lines where the only constant is my Max and Min? Can someone point me in the right direction? I would like to use VF Charts if at all possible.

 

Thank you in advance for any assistance you can provide.

 

JP

All -

 

I have created an integration that creates over 2000 records. The reason that it is so high is that I am parsing 2 very large fields on the C# side of the integration. I desperately need to reduce my API calls so the only solution is for me to parse the data in Salesforce. I do not even know where to begin. The data would come in in two very large text fields. Each value in each field has exactly 8 characters after the decimal. I would need to parse and translate these values in pair values that create multiple recors in SFDC.

 

Can someone point me in the correct direction?

 

TechEd