Every one I am trying to to send a email with attachment when oppoertunity is closed Won, but when I am trying to close more than one opprtunity at a same time then I am facing a issue that more than one attachment are send in a single email, So any one please help in to out of these probleam.
public class OpportunityPdfController {
#future(callout=true)
public static void pdfGenration(Map<Id, Id> oppIdWithAccId){
Set<Id> OppIds=oppIdWithAccId.keySet();
System.debug('OPPIDS'+ OppIds);
Map<Id, ContentVersion> contentVersionMap = createContentVersion(OppIds, oppIdWithAccId);
createContentDocumentLink(contentVersionMap);
}
private static Map<Id, ContentVersion> createContentVersion(Set<Id> OppIds, Map<Id, Id> oppIdWithAccId){
System.debug('OPPIDS2'+ OppIds);
Map<Id, ContentVersion> contentVersionMap = new Map<Id, ContentVersion>();
Blob body;
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
List<Messaging.EmailFileAttachment> attachList = new List<Messaging.EmailFileAttachment>();
List<String> sendTo= new List<String>();
List<Contact> conList=[SELECT Id, AccountId, Email FROM Contact WHERE AccountId IN: oppIdWithAccId.values() AND Email!=Null];
Map<Id, List<Contact>> ConMap= new Map<Id, List<Contact>>();
for(Id opp: oppIdWithAccId.keySet()){
ConMap.put(opp, new List<contact>());
for(Contact cc: conList){
if(cc.AccountId==oppIdWithAccId.get(opp)){
conMap.get(opp).add(cc);
}
}
}
system.debug('conList'+conList );
Map<Id, String> oppIdWithEmail= new Map<Id, String>();
for(Id OppId: OppIds){
PageReference pdf = new PageReference('/apex/InvoicePDF');
pdf.getParameters().put('Id',OppId);
ContentVersion cv=new ContentVersion();
try{
body=pdf.getContentAsPDF();
System.debug('body : ' + body);
}
catch (Exception e) {
body = Blob.valueOf('Text');
System.debug(e.getMessage());
}
cv.PathOnClient= 'Invoice'+'.pdf';
cv.Title= 'Invoice'+' '+ Date.today();
cv.IsMajorVersion = true;
cv.VersionData=body;
contentVersionMap.put(OppId, cv);
}
if(!contentVersionMap.Values().isEmpty()){
insert contentVersionMap.Values();
for(Id oid: contentVersionMap.keySet()){
Messaging.EmailFileAttachment attach= new Messaging.EmailFileAttachment();
attach.setContentType('.pdf/txt');
attach.setFileName('Invoice.pdf');
attach.setInline(false);
attach.Body = contentVersionMap.get(oid).VersionData;
attachList.add(attach);
}
For(Contact mailList: conList){
Messaging.SingleEmailMessage mail= new Messaging.SingleEmailMessage();
sendTo.add(mailList.Email);
system.debug('EmailList'+ sendTo);
mail.setToAddresses(sendTo);
mail.setSubject('Invoice');
mail.setHtmlBody('');
mail.setFileAttachments(attachList);
mails.add(mail);
}
Messaging.sendEmail(mails);
}return contentVersionMap;
}
private static void createContentDocumentLink(Map<Id, ContentVersion> idOppContentVersionMap){
Map<Id, Id> idConDocMap = new Map<Id, Id>();
List<ContentDocumentLink> ContentDocumentLinkList = new List<ContentDocumentLink>();
for(ContentVersion cv : [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:idOppContentVersionMap.Values()])
{
idConDocMap.put(cv.Id, cv.ContentDocumentId);
}
if(idConDocMap.isEmpty()) return;
for(Id OppId : idOppContentVersionMap.keySet()){
ContentVersion contentVersion = idOppContentVersionMap.get(OppId);
ContentDocumentLink cdl = New ContentDocumentLink();
cdl.LinkedEntityId = OppId;
cdl.ContentDocumentId = idConDocMap.get(contentVersion.Id);
cdl.shareType = 'V';
ContentDocumentLinkList.add(cdl);
}
if(!ContentDocumentLinkList.isEmpty()){
insert ContentDocumentLinkList;
}
}
}
Have you tried send one email rather then multiple email when testing? the attachment based on your class might not captured the first email when send many email with attachments
Related
So i have written a trigger that works perfectly fine and does exactly what i want it to do, but the thing is that it does the job on all the account, and i want it to work only on one record type of the accounts.
Can someone tell me what to add to my trigger so i can make it work only on one record type?
The following is my handler class:
public class AP03_OpportunityLineItem {
public static void preventmultipleOpportunityLineItems(List<OpportunityLineItem> listOppLineItems){
Set<Id>opportunityIds = new Set<Id>();
// get all parent IDs
for(OpportunityLineItem oli : listOppLineItems)
{
//Condition to pick certain records
opportunityIds.add(oli.OpportunityId);
}
// query for related Opportunity Line Items
Map<Id, Opportunity> mapOpportunities = new Map<Id, Opportunity>([SELECT ID,
(SELECT ID
FROM OpportunityLineItems)
FROM Opportunity
WHERE ID IN :opportunityIds]);
// opp counter of new records
Map<Id, Integer> mapOppCounter = new Map<Id, Integer>();
for(OpportunityLineItem oli : listOppLineItems)
{
if(mapOppCounter.containsKey(oli.OpportunityId))
{
mapOppCounter.put(oli.OpportunityId, mapOppCounter.get(oli.OpportunityId)+1);
}
else
{
mapOppCounter.put(oli.OpportunityId, 1);
}
}
//loop to add error if condition violated
for(OpportunityLineItem olitems : listOppLineItems)
{
if(mapOpportunities.get(olitems.OpportunityId).OpportunityLineItems.size()+mapOppCounter.get(olitems.OpportunityId)>1 || olitems.Quantity > 1)
{
olitems.addError('Ce client peut seulement loué un seul véhicule.');
}
}
}
}
The following is my PAD class:
public class PAD
{
public static String bypassTrigger; //List of bypassed triggers
public static final User user;
static {
user = [Select BypassApex__c
from User
where Id=:UserInfo.getUserId()];
bypassTrigger = ';'+ user.BypassApex__c+ ';';
System.debug('>>>>> PAD constructor : END <<<<<'+bypassTrigger);
}
/**
* Method used for the class PAD
* #param c object of type JonctionServicePrestation__c
* #return boolean
*/
public static boolean canTrigger(string Name){
return (bypassTrigger.indexof(';' + Name + ';') == -1);
}
}
And the following is my Trigger:
trigger OpportunityLineItemBeforeInsert on OpportunityLineItem (before insert) {
if(PAD.canTrigger('AP03_OpportunityLineItem')){
AP03_OpportunityLineItem.preventmultipleOpportunityLineItems(Trigger.new);
}
}
You would need to loop through your opportunitiesproducts and build a list of opportunity Id, then query the Opportunity whose Accounts in the list with the record type you want to match, and build a set of the ids that match the specified record type then check if the set contains the accountId of the opportunity being process to know if the skip or process it.
Set<Id> recordTypeOpp = new Set<ID>();
SET<Id> opportunityIds = new Set<Id>();
Id recordTypeIdYouWant = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Record Type Name').getRecordTypeId();
for(OpportunityLineItem item : listOppLineItems){
opportunityIds.add(item.OpportunityId);
}
for(Opportunity item : [SELECT Id FROM Opportunity WHERE opportunityIds IN :opportunityIds and Account.RecordTypeId = :recordTypeIdYouWant]){
recordTypeOpp.add(item.Id);
}
for(OpportunityLineItem olitems : listOppLineItems)
{
if(recordTypeOpp.contains(olitems.OpportunityId)){
//do processing
}
else {
continue;
}
}
I have created email template in sendgrid - with substitutable values;
I get the JSON payload (contains substitute values) for processing email from rabbitMQ queue. My question is how to call the sendgrid email template from Java?
I found the solution, the way to call sendgrid template and email through sendgrid as below:
SendGrid sendGrid = new SendGrid("username","password"));
SendGrid.Email email = new SendGrid.Email();
//Fill the required fields of email
email.setTo(new String[] { "xyz_to#gmail.com"});
email.setFrom("xyz_from#gmail.com");
email.setSubject(" ");
email.setText(" ");
email.setHtml(" ");
// Substitute template ID
email.addFilter(
"templates",
"template_id",
"1231_1212_2323_3232");
//place holders in template, dynamically fill values in template
email.addSubstitution(
":firstName",
new String[] { firstName });
email.addSubstitution(
":lastName",
new String[] { lastName });
// send your email
Response response = sendGrid.send(email);
This is my working soloution .
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sendgrid.*;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MailUtil {
public static void main(String[] args) throws IOException {
Email from = new Email();
from.setEmail("fromEmail");
from.setName("Samay");
String subject = "Sending with SendGrid is Fun";
Email to = new Email();
to.setName("Sam");
to.setEmail("ToEmail");
DynamicTemplatePersonalization personalization = new DynamicTemplatePersonalization();
personalization.addTo(to);
Mail mail = new Mail();
mail.setFrom(from);
personalization.addDynamicTemplateData("name", "Sam");
mail.addPersonalization(personalization);
mail.setTemplateId("TEMPLATE-ID");
SendGrid sg = new SendGrid("API-KEY");
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
private static class DynamicTemplatePersonalization extends Personalization {
#JsonProperty(value = "dynamic_template_data")
private Map<String, String> dynamic_template_data;
#JsonProperty("dynamic_template_data")
public Map<String, String> getDynamicTemplateData() {
if (dynamic_template_data == null) {
return Collections.<String, String>emptyMap();
}
return dynamic_template_data;
}
public void addDynamicTemplateData(String key, String value) {
if (dynamic_template_data == null) {
dynamic_template_data = new HashMap<String, String>();
dynamic_template_data.put(key, value);
} else {
dynamic_template_data.put(key, value);
}
}
}
}
Here is an example from last API spec:
import com.sendgrid.*;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
Email from = new Email("test#example.com");
String subject = "I'm replacing the subject tag";
Email to = new Email("test#example.com");
Content content = new Content("text/html", "I'm replacing the <strong>body tag</strong>");
Mail mail = new Mail(from, subject, to, content);
mail.personalization.get(0).addSubstitution("-name-", "Example User");
mail.personalization.get(0).addSubstitution("-city-", "Denver");
mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
}
https://github.com/sendgrid/sendgrid-java/blob/master/USE_CASES.md
Recently Sendgrid upgraded the Maven version v4.3.0 so you don't have to create additional classes for dynamic data content. Read more from this link https://github.com/sendgrid/sendgrid-java/pull/449
If you're doing a spring-boot maven project, You'll need to add the sendgrid-java maven dependency in your pom.xml. Likewise, in your application.properties file under resource folder of the project, add SENDGRID API KEY AND TEMPLATE ID under attributes such as spring.sendgrid.api-key=SG.xyz and templateId=d-cabc respectively.
Having done the pre-setups. You can create a simple controller class as the one given below:
Happy Coding!
#RestController
#RequestMapping("/sendgrid")
public class MailResource {
private final SendGrid sendGrid;
#Value("${templateId}")
private String EMAIL_TEMPLATE_ID;
public MailResource(SendGrid sendGrid) {
this.sendGrid = sendGrid;
}
#GetMapping("/test")
public String sendEmailWithSendGrid(#RequestParam("msg") String message) {
Email from = new Email("bijay.shrestha#f1soft.com");
String subject = "Welcome Fonesal Unit to SendGrid";
Email to = new Email("birat.bohora#f1soft.com");
Content content = new Content("text/html", message);
Mail mail = new Mail(from, subject, to, content);
mail.setReplyTo(new Email("bijay.shrestha#f1soft.com"));
mail.setTemplateId(EMAIL_TEMPLATE_ID);
Request request = new Request();
Response response = null;
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
response = sendGrid.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return "Email was successfully sent";
}
}
This is based on verision com.sendgrid:sendgrid-java:4.8.3
Email from = new Email(fromEmail);
Email to = new Email(toEmail);
String subject = "subject";
Content content = new Content(TEXT_HTML, "dummy value");
Mail mail = new Mail(from, subject, to, content);
// Using template to send Email, so subject and content will be ignored
mail.setTemplateId(request.getTemplateId());
SendGrid sendGrid = new SendGrid(SEND_GRID_API_KEY);
Request sendRequest = new Request();
sendRequest.setMethod(Method.POST);
sendRequest.setEndpoint("mail/send");
sendRequest.setBody(mail.build());
Response response = sendGrid.api(sendRequest);
You can also find fully example here:
Full Email object Java example
I am working on a plugin on Delete button, when ever I delete any selected record all the distinct(Selected record) should be deleted as well.
In my case I have an Attendee which is invited in a meeting, The Attendee also have some discussion point records and Action Items records in it, As per the requirement when I will delete my Meeting Attendee it should delete this Attendee where it has any discussion point record and Action items record.Need help on this regard.
Below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
namespace SFDSendEmail.SFDDeleteAttendee.Class
{
public class SFDDeleteAttendee : IPlugin
{
Guid Internaluser;
Guid Externaluser;
private IOrganizationService _sdk = null;
public void Execute(IServiceProvider serviceProvider)
{
try
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_sdk = (IOrganizationService)factory.CreateOrganizationService(context.UserId);
if (context.IsExecutingOffline || context.IsOfflinePlayback)
return;
// The InputParameters collection contains all the data passed
// in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is EntityReference)
{
// EntityReference RequiredAttendee = context.InputParameters["new_requiredattendee"] as EntityReference;
// Entity entity = _sdk.Retrieve("new_requiredattendee", ((EntityReference)RequiredAttendee["new_requiredattendeeid"]).Id, new ColumnSet(true));
// Entity eUser = _sdk.Retrieve(RequiredAttendee.LogicalName, RequiredAttendee.Id, new ColumnSet(true));
EntityReference RequiredAttendee = (EntityReference)context.InputParameters["Target"];
Entity eUser = _sdk.Retrieve(RequiredAttendee.LogicalName, RequiredAttendee.Id, new ColumnSet(true));
if (context.MessageName == "Delete")
{
if (eUser.LogicalName != "new_requiredattendee")
{
return;
}
else
{
//If User Selects the Interner User for Deletion
if (eUser.Attributes.Contains("new_internaluser"))
{
//Save Internal User ID
Internaluser = ((EntityReference)eUser["new_internaluser"]).Id;
//Function to fetch the Meeting Attendee with the Above ID
Guid VerifyAttendee = VerifyMeetingAttendee(eUser,_sdk,Internaluser);
//If its the Meeting Attendee
if (VerifyAttendee != null)
{
//Get the Attendee with its Discussion Point
Guid AttendeewithDp = VerifyDPMeetingAttendee(eUser, _sdk, Internaluser);
if (AttendeewithDp != null)
{
//Get the Attendee with Action item
Guid AttendeewithAI = VerifyAIMeetingAttendee(eUser, _sdk, Internaluser);
if (AttendeewithAI != null)
{
//DO your code here....................................
_sdk.Delete("new_requiredattendee", AttendeewithAI);
}
}
}
}
//If User Selects the Interner User for Deletion
else if (eUser.Attributes.Contains("new_externaluser"))
{
//Save Internal User ID
Externaluser = ((EntityReference)eUser.Attributes["new_externaluser"]).Id;
//Function to fetch the Meeting Attendee with the Above ID
Guid verifyExternalAttendee = VerifyExternalMeetingAttendee(eUser,_sdk,Externaluser);
if (verifyExternalAttendee != null)
{
//Get the Attendee with its Discussion Point
Guid EXAttendeewithDp = VerifyEXDPMeetingAttendee(eUser, _sdk, Externaluser);
if (EXAttendeewithDp != null)
{
//Get the Attendee with Action item
Guid EXAttendeewithAI = VerifyEXAIMeetingAttendee(eUser, _sdk, Externaluser);
if (EXAttendeewithAI != null)
{
//DO your code here....................................
_sdk.Delete("new_requiredattendee", EXAttendeewithAI);
}
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
}
}
//Get Internal Meeting Attendee
public Guid VerifyMeetingAttendee(Entity RequiredAttendee,IOrganizationService _orgService,Guid user)
{
QueryExpression GetMeetingAttendees = new QueryExpression();
GetMeetingAttendees.EntityName = "new_requiredattendee";
GetMeetingAttendees.ColumnSet = new ColumnSet("new_internaluser");
GetMeetingAttendees.Criteria.AddCondition("new_mom", ConditionOperator.Equal, RequiredAttendee["new_mom"]);
GetMeetingAttendees.Criteria.AddCondition("new_internaluser", ConditionOperator.Equal,user);
GetMeetingAttendees.Criteria.AddCondition("new_actionitem", ConditionOperator.Null);
GetMeetingAttendees.Criteria.AddCondition("new_discussionpoint", ConditionOperator.Null);
GetMeetingAttendees.Criteria.AddCondition("new_externaluser", ConditionOperator.Null);
EntityCollection GMA = _orgService.RetrieveMultiple(GetMeetingAttendees);
return (Guid)GMA[0]["new_internaluser"];
}
//Get Internal Meeting Attendee with Discussion Point
public Guid VerifyDPMeetingAttendee(Entity RequiredAttendee, IOrganizationService _orgService, Guid user)
{
QueryExpression GetDPMeetingAttendees = new QueryExpression();
GetDPMeetingAttendees.EntityName = "new_requiredattendee";
GetDPMeetingAttendees.ColumnSet = new ColumnSet("new_internaluser");
GetDPMeetingAttendees.Criteria.AddCondition("new_mom", ConditionOperator.Equal, RequiredAttendee["new_mom"]);
GetDPMeetingAttendees.Criteria.AddCondition("new_internaluser", ConditionOperator.Equal,user);
GetDPMeetingAttendees.Criteria.AddCondition("new_actionitem", ConditionOperator.Null);
GetDPMeetingAttendees.Criteria.AddCondition("new_discussionpoint", ConditionOperator.NotNull);
GetDPMeetingAttendees.Criteria.AddCondition("new_externaluser", ConditionOperator.Null);
EntityCollection GMA = _orgService.RetrieveMultiple(GetDPMeetingAttendees);
return (Guid)GMA[0]["new_internaluser"];
}
//Get Internal Meeting Attendee with Action Items
public Guid VerifyAIMeetingAttendee(Entity RequiredAttendee, IOrganizationService _orgService, Guid user)
{
QueryExpression GetDPMeetingAttendees = new QueryExpression();
GetDPMeetingAttendees.EntityName = "new_requiredattendee";
GetDPMeetingAttendees.ColumnSet = new ColumnSet("new_internaluser");
GetDPMeetingAttendees.Criteria.AddCondition("new_mom", ConditionOperator.Equal, RequiredAttendee["new_mom"]);
GetDPMeetingAttendees.Criteria.AddCondition("new_internaluser", ConditionOperator.Equal,user);
GetDPMeetingAttendees.Criteria.AddCondition("new_actionitem", ConditionOperator.NotNull);
GetDPMeetingAttendees.Criteria.AddCondition("new_externaluser", ConditionOperator.Null);
EntityCollection GMA = _orgService.RetrieveMultiple(GetDPMeetingAttendees);
return (Guid)GMA[0]["new_internaluser"];
}
//Get External Meeting Attendee
public Guid VerifyExternalMeetingAttendee(Entity RequiredAttendee, IOrganizationService _orgService, Guid user)
{
QueryExpression GetMeetingAttendees = new QueryExpression();
GetMeetingAttendees.EntityName = "new_requiredattendee";
GetMeetingAttendees.ColumnSet = new ColumnSet("new_externaluser");
GetMeetingAttendees.Criteria.AddCondition("new_mom", ConditionOperator.Equal, RequiredAttendee["new_mom"]);
GetMeetingAttendees.Criteria.AddCondition("new_externaluser", ConditionOperator.Equal, user);
GetMeetingAttendees.Criteria.AddCondition("new_actionitem", ConditionOperator.Null);
GetMeetingAttendees.Criteria.AddCondition("new_discussionpoint", ConditionOperator.Null);
GetMeetingAttendees.Criteria.AddCondition("new_internaluser", ConditionOperator.Null);
EntityCollection GMA = _orgService.RetrieveMultiple(GetMeetingAttendees);
return (Guid)GMA[0]["new_externaluser"];
}
//Get External Meeting Attendee with Discussion Point
public Guid VerifyEXDPMeetingAttendee(Entity RequiredAttendee, IOrganizationService _orgService, Guid user)
{
QueryExpression GetMeetingAttendees = new QueryExpression();
GetMeetingAttendees.EntityName = "new_requiredattendee";
GetMeetingAttendees.ColumnSet = new ColumnSet("new_externaluser");
GetMeetingAttendees.Criteria.AddCondition("new_mom", ConditionOperator.Equal, RequiredAttendee["new_mom"]);
GetMeetingAttendees.Criteria.AddCondition("new_externaluser", ConditionOperator.Equal, user);
GetMeetingAttendees.Criteria.AddCondition("new_actionitem", ConditionOperator.Null);
GetMeetingAttendees.Criteria.AddCondition("new_discussionpoint", ConditionOperator.NotNull);
GetMeetingAttendees.Criteria.AddCondition("new_internaluser", ConditionOperator.Null);
EntityCollection GMA = _orgService.RetrieveMultiple(GetMeetingAttendees);
return (Guid)GMA[0]["new_externaluser"];
}
//Get External Meeting Attendee with Action Item
public Guid VerifyEXAIMeetingAttendee(Entity RequiredAttendee, IOrganizationService _orgService, Guid user)
{
QueryExpression GetMeetingAttendees = new QueryExpression();
GetMeetingAttendees.EntityName = "new_requiredattendee";
GetMeetingAttendees.ColumnSet = new ColumnSet("new_externaluser");
GetMeetingAttendees.Criteria.AddCondition("new_mom", ConditionOperator.Equal, RequiredAttendee["new_mom"]);
GetMeetingAttendees.Criteria.AddCondition("new_externaluser", ConditionOperator.Equal, user);
GetMeetingAttendees.Criteria.AddCondition("new_actionitem", ConditionOperator.NotNull);
GetMeetingAttendees.Criteria.AddCondition("new_internaluser", ConditionOperator.Null);
EntityCollection GMA = _orgService.RetrieveMultiple(GetMeetingAttendees);
return (Guid)GMA[0]["new_externaluser"];
}
}
}
I'm having a little trouble understanding the issue here, but here's my thoughts.
1) If it is rolling back the delete, then there is either an error with the delete or with cascading deletes underneath this one. Providing the exception message would go a long way to helping us troubleshoot your problem.
2) You can make your code much more concise and readable using LINQ queries instead of the CRM QueryExpression. Another area for improvement is the exact same code multiple times with 1 minor tweak - aka the branches for attributes.contains("new_internaluser") and attributes.contains("new_external") user could be much improved - see below).
//Add this method to the class
internal void deleteUser(string userString){
user = ((EntityReference)eUser[userString]).Id;
//Function to fetch the Meeting Attendee with the Above ID
Guid VerifyAttendee = VerifyMeetingAttendee(eUser,_sdk,user);
//If its the Meeting Attendee
if (VerifyAttendee != null)
{
//Get the Attendee with its Discussion Point
Guid AttendeewithDp = VerifyDPMeetingAttendee(eUser, _sdk, user);
if (AttendeewithDp != null)
{
//Get the Attendee with Action item
Guid AttendeewithAI = VerifyAIMeetingAttendee(eUser, _sdk, user);
if (AttendeewithAI != null)
{
//DO your code here....................................
_sdk.Delete("new_requiredattendee", AttendeewithAI);
}
}
}
}
//And call it with these few simple lines within your main execute method:
if (eUser.Attributes.Contains("new_internaluser"))
{
deleteUser("new_internaluser");
}
//If User Selects the Interner User for Deletion
else if (eUser.Attributes.Contains("new_externaluser"))
{
deleteUser("new_externaluser");
}
i am developing a smartGWt application that needs to filter list grid content by date and by other staff, every thing is working correctly except the date filtration, this is how i am defining the date fields :
registeredDate = new DataSourceDateField("registrationDate", voc.registeredDate());
registeredDate.setRequired(true);
verificationDate = new DataSourceDateField("lastVerificationDate", voc.verificationDate());
verificationDate.setRequired(true);
the same as every other field
this is how i fill records :
registeredUsersRecords = new ListGridRecord[registeredUsers.length()];
ListGridRecord record = new ListGridRecord();
record.setAttribute(ID, user.getId());
record.setAttribute("firstName", user.getFirstName());
record.setAttribute("lastName", user.getLastName());
record.setAttribute("email", user.getEmail());
record.setAttribute("userMainType", type);
record.setAttribute("isActivated", (user.isActivated())? voc.active(): voc.inActive());
record.setAttribute("country", user.getSelectedCountry().getValue());
record.setAttribute("companyName", user.getCompanyName());
record.setAttribute("registrationDate", user.getRegistrationDate());
record.setAttribute("lastVerificationDate", user.getVerificationDate());
registeredUsersRecords[i] = record;
and then i put them into datasource :
DataSource ds = new DataSource();
ds.setClientOnly(true);
ds.setFields(fName, lName, email, type,typeDetails, status, country, companyName, registeredDate,verificationDate);
for(int i = 0; i< registeredUsersRecords.length; i++){
ds.addData(registeredUsersRecords[i]);
}
registeredUsersListGrid.setDataSource(ds);
registeredUsersListGrid.fetchData();
You have not shared a complete code.
Still I am trying to provide you a sample code. Please have a look.
public class SmartGWTProject implements EntryPoint {
public void onModuleLoad() {
class User {
private int id;
private String firstName;
private Date registrationDate;
public User(int id, String firstName, Date registrationDate) {
this.id = id;
this.firstName = firstName;
this.registrationDate = registrationDate;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public Date getRegistrationDate() {
return registrationDate;
}
}
DateTimeFormat format = DateTimeFormat.getFormat("MM/dd/yyyy");
User[] registeredUsers = new User[] { new User(1, "a", format.parse("01/20/2014")),
new User(2, "b", format.parse("05/20/2013")),
new User(3, "c", format.parse("02/20/2014")) };
ListGridRecord[] registeredUsersRecords = new ListGridRecord[registeredUsers.length];
for (int i = 0; i < registeredUsers.length; i++) {
User user = registeredUsers[i];
ListGridRecord record = new ListGridRecord();
record.setAttribute("id", user.getId());
record.setAttribute("firstName", user.getFirstName());
record.setAttribute("registrationDate", user.getRegistrationDate());
registeredUsersRecords[i] = record;
}
DataSourceDateField registeredDate = new DataSourceDateField("registrationDate", "Date");
DataSourceTextField firstName = new DataSourceTextField("firstName", "Name");
DataSourceIntegerField id = new DataSourceIntegerField("id", "ID");
id.setRequired(true);
id.setPrimaryKey(true);
id.setHidden(true);
DataSource ds = new DataSource();
ds.setClientOnly(true);
ds.setFields(id, firstName, registeredDate);
for (int i = 0; i < registeredUsersRecords.length; i++) {
ds.addData(registeredUsersRecords[i]);
}
ListGrid registeredUsersListGrid = new ListGrid();
registeredUsersListGrid.setDataSource(ds);
registeredUsersListGrid.fetchData();
registeredUsersListGrid.draw();
}
}
i have a mission to make a plug-in in crm 4 which should 1. put in the subject field of an email the name of the account and then 2. put the contact list of account to the cc field of the email.
the first thing i did and it work, but the second... not so much...
i have seen some samples but none of them was close to halp me...
i would like to have help and explain of how to find the list of the contact that belong to the account and then put the list in the cc field.
here is the begining...:
namespace mail
{
public class Class1 : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity = null;
if (context.InputParameters.Properties.Contains("Target") &&
context.InputParameters.Properties["Target"] is DynamicEntity)
{
entity = (DynamicEntity)context.InputParameters.Properties["Target"];
if (entity.Name != EntityName.account.ToString())
{
return;
}
}
else
{
return;
}
try
{
// updating the subject of the email
ICrmService service = context.CreateCrmService(true);
account accountRecord = (account)service.Retrieve("account", ((Key)entity.Properties["accountid"]).Value, new ColumnSet(new string[] { "name" }));
String str = String.Empty;
str = accountRecord.name.ToString();
DynamicEntity followup = new DynamicEntity();
followup.Name = EntityName.email.ToString();
followup.Properties = new PropertyCollection();
followup.Properties.Add(new StringProperty("subject", str));
//updating the CC of the email
TargetCreateDynamic targetCreate = new TargetCreateDynamic();
targetCreate.Entity = followup;
CreateRequest create = new CreateRequest();
create.Target = targetCreate;
CreateResponse created = (CreateResponse)service.Execute(create);
}
catch
{
throw new InvalidPluginExecutionException(
"An error occurred in the AccountUpdateHandler plug-in.");
}
}
}
}
You can try something like this,
List<BusinessEntity> contactList = GetNeededContacts(crmService, sourceEntity);
email targetEmail = GetTargetEmail(crmService, emailid);
foreach (DynamicEntity contact in contactList)
{
activityparty contActParty = new activityparty() { partyid = new Lookup("contact", contact.contactid.Value };
List<activityparty> tmpList = targetEmail.cc.ToList();
tmpList.Add(contActParty);
targetEmail.cc = tmpList.ToArray();
}
crmService.Update(targetEmail);
You only have to develop the function to get the contact, user or account references.