Salesforce: Apex trigger to check whether email domain exists - triggers

I want to find out whether the email domain exist in the database. Eg: If xxx#abc.com is going to be inserted, I want to check email with the same domain(abc.com) already exist or not. Following is the code to check the whole email exist.
trigger trig_Contact_webToContact on Contact (before insert)
{
final String errMsg = 'The email already exists on another Contact: ';
Set< String > emailSet = new Set< String >();
for( Contact c : Trigger.new ) emailSet.add( c.Email );
Map< String, Id > duplicateContactMap = new Map< String, Id >();
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
duplicateContactMap.put( c.Email, c.Id );
for( Contact c : Trigger.new ){
Id duplicateContactId = duplicateContactMap.get( c.Email );
if( duplicateContactId != null )
c.addError( errMsg + duplicateContactId );
}
}

First, get only domain from email, but not the whole email:
Set< String > emailDomainSet = new Set< String >();
for( Contact c : Trigger.new ) {
if (String.isBlank(c.Email)) continue;
int indexOfAt = c.Email.indexOf('#');
if (indexOfAt > 0) emailDomainSet.add( c.Email.substring(indexOfAt) );
}
then, in your case, you need to use query(queryString) method. Compose a SOQL string first
string queryString = 'select name from Contact where ';
string whereClause = ' ';
for (string domainItem : emailDomainSet) {
whereClause += ' or Email like \'%'+domainItem + '\' ';
}
whereClause = whereClause.substring(4);//remove first or in where clause
queryString += whereClause;
then, run it.
Instead of
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
you should put
for( Contact c : (List<Contact>)Database.query(queryString) )

Related

salesforce compare standard obj and custom object and assign value

I have custom obj "A" and Standard obj Case. Case standard obj has lookup to custom obj "A". there is a field between the two objects called Customer_ID__c. I wrote a Trigger (before Insert, Before Update) to associated the case record to the correct existing custom obj "A" record if "Case.Custom_Id__c" match the one in the Custom obj "A". Unfortunate it is not happening and I'm not sure where to look.
trigger IAACaseRelateASAP on Case (before insert, before update) {
Id recordtypes = [Select Id, name
From RecordType
Where SobjectType = 'Case'
AND Name = 'I Buy'
LIMIT 1].Id;
Set<String> casId = new Set<String>();
for(Case cs : Trigger.new)
{
if(cs.RecordtypeId == recordtypes && cs.Type == 'Contact Me')
{
if(cs.custm_Obj_A_Name__lookupfield__c == null && (cs.Customer_ID__c != null || cs.Customer_ID__c !='0'))
{
casId.add(cs.Customer_ID__c);
}
}
}
system.debug('Case Set Ids' + casId);
List<A__c> aList = [Select Customer_ID__c, Id
From A__c
Where Customer_ID__c IN: casId
AND
A__c != 'Provider'];
System.Debug('equals' + aList);
Map<String, A__c> aMapId = new Map<String, A__c>();
for(A__c aAcct : aList)
{
aMapId.put(aAcct.Customer_ID__c, aAcct);
}
for(Case cas : Trigger.new)
{
if(cas.RecordtypeId == recordtypes && cas.Type == 'Contact Me')
{
if(cas.custm_Obj_A_Name__lookupfield__c == null && (cas.Customer_ID__c != null || cas.Customer_ID__c !='0'))
{
if(aMapId.containsKey(cas.Customer_ID__c))
{
A__c aAcct = aMapId.get(cas.Customer_ID__c);
System.Debug('Case IAA ASAP Account value: ' + asapAcct);
}
}
}
}
}
It might be best when looping through your cases to build your set of Customer_ID__c ids to also build a List of cases with customer ids so that you don't have to loop through the entire new list a second time. There are a couple other issues with the trigger in general but I'll ignore those and just focus on what you asked. Think your issue is that you don't actually set the case field in this area:
if(aMapId.containsKey(cas.Customer_ID__c))
{
A__c aAcct = aMapId.get(cas.Customer_ID__c);
System.Debug('Case IAA ASAP Account value: ' + asapAcct);
}
It should be :
if(aMapId.containsKey(cas.Customer_ID__c))
{
cas.custm_Obj_A_Name__lookupfield__c = aMapId.get(cas.Customer_ID__c).Id;
}

How should I get distinct Record in linq query

Hi I have tried below query to get the distinct record but I am not able to get the distinct record from below query.
var query = (from sr in db.StudentRequests
join r in db.Registrations on sr.RegistrationId equals r.RegistrationId
join cc in db.Campus on r.CampusId equals cc.CampusId
join c in db.Classes on sr.ClassId equals c.ClassId
from tc in db.TutorClasses.Where(t => t.ClassId == sr.ClassId).DefaultIfEmpty()
from srt in db.StudentRequestTimings.Where(s => s.StudentRequestId == sr.StudentRequestId).DefaultIfEmpty()
from tsr in db.TutorStudentRequests.Where(t => t.StudentRequestId == srt.StudentRequestId && t.TutorId == registrationid).DefaultIfEmpty()
where tc.RegistrationId == registrationid
select new
{
StudentRequestId = sr.StudentRequestId,
RegistrationId = sr.RegistrationId,
Location = sr.Location,
PaymentMethod = sr.PaymentMethod,
CreatedOn = sr.CreatedOn,
ClassName = c.ClassName,
CampusName = cc.CampusName,
StatusId = tsr.StatusId == null ? 1 : tsr.StatusId,
Time = db.StudentRequestTimings.Where(p => p.StudentRequestId == sr.StudentRequestId)
.Select(p => p.FromTime.ToString().Replace("AM", "").Replace("PM", "") + "-" + p.ToTime)
}).Distinct().ToList().ToPagedList(page ?? 1, 3);
But I am getting error as
The 'Distinct' operation cannot be applied to the collection
ResultType of the specified argument.\r\nParameter name: argument
So I had removed the .Distinct() from the above query and below that code I had written code as
query = query.Distinct().ToList();
But still the duplicate record was showing
So I had tried Group by clause to get distinct record but over there also I am facing the issue.Please Review below code
query = query.ToList().GroupBy(x => new { x.StudentRequestId, x.StatusId, x.Location, x.RegistrationId, x.PaymentMethod, x.CreatedOn, x.ClassName, x.CampusName})
.Select(group => new
{
StudentRequestId = group.Key.StudentRequestId,
StatusId = group.Key.StatusId,
Location = group.Key.Location,
RegistrationId = group.Key.RegistrationId,
PaymentMethod = group.Key.PaymentMethod,
CreatedOn = group.Key.CreatedOn,
ClassName = group.Key.ClassName,
CampusName = group.Key.CampusName,
Time1 = group.Key.Time
});
But I am getting error for time as
How can I get the distinct Value?
Also make in concern that I am using ToPagedList in the query
The actual issue is coming from Time column, If I remove that column all things are working fine.
I had added Group by clause at the end of the query as suggested by #Rajaji and that worked for me.
var query = (from sr in db.StudentRequests
join r in db.Registrations on sr.RegistrationId equals r.RegistrationId
join cc in db.Campus on r.CampusId equals cc.CampusId
join c in db.Classes on sr.ClassId equals c.ClassId
from tc in db.TutorClasses.Where(t => t.ClassId == sr.ClassId).DefaultIfEmpty()
from srt in db.StudentRequestTimings.Where(s => s.StudentRequestId == sr.StudentRequestId).DefaultIfEmpty()
from tsr in db.TutorStudentRequests.Where(t => t.StudentRequestId == srt.StudentRequestId && t.TutorId == registrationid).DefaultIfEmpty()
where tc.RegistrationId == registrationid
select new
{
StudentRequestId = sr.StudentRequestId,
RegistrationId = sr.RegistrationId,
Location = sr.Location,
PaymentMethod = sr.PaymentMethod,
CreatedOn = sr.CreatedOn,
ClassName = c.ClassName,
CampusName = cc.CampusName,
StatusId = tsr.StatusId == null ? 1 : tsr.StatusId,
Time = db.StudentRequestTimings.Where(p => p.StudentRequestId == sr.StudentRequestId).Select(p => p.FromTime.ToString().Replace("AM", "").Replace("PM", "") + "-" + p.ToTime)
}).ToList().GroupBy(p => new { p.StudentRequestId }).Select(g => g.First()).ToList();

mvc entity framework select with dynamic where clause

I am doing a asp.net-mvc with entity-framework App.
I have a select instruction, where I need to have a dymanic where condition.
It is a common case where you have a filter composed by a string like "aaaa bbbb cccc". I need to bring all data that contains all the filter string or part of it.
I doing part ot it witt Split function, but it is difficult to get all posible combinations.
I Would rather use a Store Procedure. But the porpose of it, is to use Entity Framework.
As far I did this.
public IEnumerable<UploadSearch> GetUploadsBySearch(string search)
{
IEnumerable<UploadSearch> viewModel = (from uploads in _db.Uploads
.Where(p => p.ProcessState_id == Security.APPROVED && p.Finder.Contains(search))
.OrderByDescending(p => p.UploadDate)
select new UploadSearch
{
User_id = uploads.User_id,
UserName = uploads.Users.Name,
UserLastName = uploads.Users.LastName,
});
And I Add a for instruction to loop throu the string,
string[] param = search.Replace(" "," ").Split(' ');
string _param = "";
int large = param.Length;
for (int i=0;i<large-1;i++)
{
_param +=param[i] ' ' + param[i + 1];
IEnumerable<UploadSearch> _viewModel = (from uploads in _db.Uploads
.Where(p => p.ProcessState_id == Security.APPROVED && p.Finder.Contains(_param))
.OrderByDescending(p => p.UploadDate)
select new UploadSearch
{
User_id = uploads.User_id,
UserName = uploads.Users.Name,
UserLastName = uploads.Users.LastName,
});
viewModel = viewModel.Union(_viewModel);
}
And I use a Union clause.
But There has to be another way to do it.
Any Ideas?
You should use LinqKit, it has a PredicateBuilder class that allows you to dynamically build queries
https://github.com/scottksmith95/LINQKit#predicatebuilder
IQueryable<Product> SearchProducts (params string[] keywords)
{
var predicate = PredicateBuilder.New<Product>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or (p => p.Description.Contains (temp));
}
return dataContext.Products.Where (predicate);
}

Test Coverage fails on before insert / before update Apex trigger

I have this very simple before insert / update trigger on Opportunity that auto-selects the Price Book based on a dropdown value containing Sales Office (State) location info.
Here's my Trigger:
trigger SelectPriceBook on Opportunity ( before insert, before update ) {
for( Opportunity opp : Trigger.new ) {
// Change Price Book
// New York
if( opp.Campus__c == 'NYC' )
opp.Pricebook2Id = PB_NYC; // contains a Pricebook's ID
// Atlanta
if( opp.Campus__c == 'ATL' )
opp.Pricebook2Id = PB_ATL; // contains another Pricebook's ID
}
}
Here's my Test Class:
#isTest (SeeAllData = true)
public class SelectPriceBookTestClass {
static testMethod void validateSelectPriceBook() {
// Pricebook IDs
ID PB_NYC = 'xxxx';
ID PB_ATL = 'xxxx';
// New Opp
Opportunity opp = new Opportunity();
opp.Name = 'Test Opp';
opp.Office__c = 'NYC';
opp.StageName = 'Quote';
// Insert
insert opp;
// Retrive inserted opportunity
opp = [SELECT Pricebook2id FROM Opportunity WHERE Id =:opp.Id];
System.debug( 'Retrieved Pricebook Id: ' + opp.Pricebook2Id );
// Change Campus
opp.Office__c = 'ATL';
// Update Opportunity
update opp;
// Retrive updated opportunity
opp = [SELECT Pricebook2id FROM Opportunity WHERE Id =:opp.Id];
System.debug( 'Retrieved Updated Pricebook Id: ' + opp.Pricebook2Id );
// Test
System.assertEquals( PB_ATL, opp.Pricebook2Id );
}
}
The test runs report 0% test coverage.
Also, on similar lines I have another before insert trigger that sets the Owner of an Event same as the Owner of the parent Lead. Here's the code:
trigger AutoCampusTourOwner on Event( before insert ) {
for( Event evt : Trigger.new ) {
// Abort if other kind of Event
if( evt.Subject != 'Visit' )
return;
// Set Owner Id
Lead parentLead = [SELECT OwnerId FROM Lead WHERE Id = :evt.WhoId];
evt.OwnerId = parentLead.OwnerId;
}
}
This, too, is causing 0% coverage - my guess is that it's got something to do with the for loops in both. I know I'm seriously flouting DML rules by invoking SOQL query inside a for loop, but for my purposes it should be fine as these Events are created manually and only one at a time - so there are no scopes of governor limits kicking in due to bulk inserts.
The code in both cases work 100%. Please suggest a fix for the test cases.
Have you tried trigger.old ?? My thinking is, when you update the office in your test class from NYC to ATL, the value 'NYC' will be in trigger.old, and that's what you want to check in your trigger.
I could be wrong since i'm new to apex too, but try it and let me know what happens.
For the first trigger don't do anything rather just create opportunity and execute like this.
Test class for SelectPriceBook
#isTest
private class TriggerTestClass {
static testmethod void selectPriceTest(){
Opportunity opps = new Opportunity(
Name= 'Test Opps',
CloseDate = System.today().addDays(30),
StageName = 'Prospecting',
ForecastCategoryName = 'Pipeline',
Office__c = 'NYC');
insert opps;
Opportunity opps2 = new Opportunity(
Name= 'Test Opps 2',
CloseDate = System.today().addDays(28),
StageName = 'Prospecting',
ForecastCategoryName = 'Pipeline',
Office__c = 'ATL');
insert opps2;
}
}
It will give you good test coverage and I don't know what are you trying to do in AutoCampusTourOwner!
i have test class for these
trigger ClientEmailTrigger on inflooens__Client_Email__c (after insert, after update, before insert, before update) {
ApexTriggerSettings__c setting = ApexTriggerSettings__c.getValues('Inflooens Trigger Settings');
if(setting != NULL && setting.ClientEmailTrigger__c == TRUE){
AuditTrailController objAdt = new AuditTrailController();
if(Trigger.isAfter){
if(Trigger.isUpdate){
System.debug('In Update Client Email Record');
objAdt.insertAuditRecord(Trigger.newMap, 'inflooens__Client_Email__c', Trigger.new.get(0).Id, Trigger.oldMap);
}
if(Trigger.isInsert){
objAdt.insertAuditRecord(Trigger.newMap, 'inflooens__Client_Email__c', null , null);
}
}
}
}

Apex - Salesforce.com - I need help writing an APEX class to test my working trigger - Chatter - Monitor specific keywords

Here is my working trigger
trigger CheckChatterPostsOnNSP on FeedItem (before insert) {
Set<Id> nspIds = new Set<Id>();
//Get the NSP that will be updated
List<Non_Standard_Pricing__c> nsp2Update = new List<Non_Standard_Pricing__c>();
//Get the key prefix for the NSP object via a describe call.
String nspKeyPrefix = Non_Standard_Pricing__c.sObjectType.getDescribe().getKeyPrefix();
//Get the Id of the user
Id profileId = UserInfo.getProfileId();
for (FeedItem f: trigger.new) {
String parentId = f.parentId;
if(profileId == '00e30000000eWXR') {// Users profile must be Sales and Service
//We compare the start of the 'parentID' field to the NSP key prefix to
//restrict the trigger to act on posts made to the NSP object.
if (
parentId.startsWith(nspKeyPrefix) &&
(
f.Body.contains('***APPROVED BY CHANNEL***') ||
f.Body.contains('***APPROVED BY CSM***') ||
f.Body.contains('[APPROVED BY CHANNEL]') ||
f.Body.contains('[APPROVED BY CSM]')
)
){
nspIds.add(f.parentId);
}
}
}
List < Non_Standard_Pricing__c > nsps = [select id, Pre_Approved_Service_Discount__c, ownerId
from Non_Standard_Pricing__c where id in :nspIds];
for (Non_Standard_Pricing__c n: nsps) {
//We compare the creator of the Chatter post to the NSP Owner to ensure
//that only authorized users can close the NSP using the special Chatter 'hot-key'
n.Pre_Approved_Service_Discount__c = true;
nsp2Update.add(n);
}
update nsp2Update;
}
Here is my attempt to write an APEX Test Class
#isTest
public class CheckChatterPostsOnNSPTEST {
static testMethod void CheckChatterPostsOnNSPTEST() {
//Create and insert opp
Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Probability = 95, CloseDate=system.today());
insert opp;
//Create and insert NSP
Non_Standard_Pricing__c NSP = new Non_Standard_Pricing__c(Opportunity__c = opp.Id, Status__c = 'Open');
insert NSP;
//Find user with Profile = Sales and Service
Profile SalesNService = [Select id from Profile where Name = 'Sales and Service' limit 1];
User u = new User(
Alias = 'standt',
Email='standarduser#testorg.com',
EmailEncodingKey='UTF-8',
LastName='Testing',
LanguageLocaleKey='en_US',
LocaleSidKey='en_US',
ProfileId = SalesNService.Id,
TimeZoneSidKey='America/Los_Angeles',
UserName='standarduser#testorg.com'
);
System.runAs(u)
{
//Create FeedItem entry with text '[APPROVED BY CHANNEL]'
FeedItem post = new FeedItem();
post.body = '[APPROVED BY CHANNEL]';
//Now update the opportunites to invoke the trigger
Test.startTest();
insert post;
Test.stopTest();
}
//Assertion Testing
for(Opportunity o : [select Id, Name, Primary_NSP__r.Pre_Approved_Service_Discount__c from Opportunity where Id = :opp.Id]){
system.assert(o.Primary_NSP__r.Pre_Approved_Service_Discount__c = true);
}
}
}
I'm getting the following errors
Message: System.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.CheckChatterPostsOnNSPTEST.CheckChatterPostsOnNSPTEST: line 14, column 1
Any help is greatly appreciated.
That'd be pointing to this line:
Profile SalesNService = [Select id from Profile where Name = 'Sales and Service' limit 1];
Simply check if this query returns something? Typo in the profile name (maybe you have them with underscores or "Sales & Service")? Maybe there's no such profile in org at all (for example if you've created such one on production but the sandbox you're in was not refreshed afterwards)?
I'm afraid we can't help you more than that ;) It can't be even related to API versions, "seeAllData" etc because docs say Profiles are still visible.