We created an opportunity and expected it to have an associated task, but it didn’t. Make sure your trigger inserts the task into the database - trigger.io

We created an opportunity and expected it to have an associated task, but it didn’t. Make sure your trigger inserts the task into the database
2
3
4
5
6
7
8
9
10
11
12
13
14
15
trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
List taskListToInsert = new List();
for(Opportunity opp : [Select Id,StageName from Opportunity
where Id in :Trigger.New AND StageName = 'Closed Won'])
{
taskListtoInsert.add(new Task(Subject ='Follow Up Test Task',WhatId = opp.Id));
}
if(taskListtoInsert.size()>0)
{
insert taskListtoInsert;
}
}

Instead this line
List taskListToInsert = new List();
try this
List<Task> taskListToInsert = new List<Task>();
You should also check if you have any process builder activated that may be causing this problem

Related

EF6: Add Object with Foreign Key to Multiple Tables But What if Foreign Key Already Exist Somewhere? (+trying to have no round trips to check IDs)

I have table ProjekRumah and ProjekKMDetails.
When I use entities.SaveChanges() on ProjekRumah data, new row with ProjectID will yield its Identity. Suppose that number is 7.
Then I take this ProjekID=7, to create ProjekKMDetails data. Then, entities.SaveChanges(). Repeat same step Table1, Table2, Table3, Table 4 and so on with ProjectID=7 as Foreign Key.
All is fine on sunny day. What if ProjekID=7 already exists in one of these table, suppose hypothetically in Table3.
I understand this is not suppose to happen. But suppose its Friday the 13th an intern might drop all constraints and forgot to truncate Table3. Or some evil data corruption.
using (MyDBEntities entities = new MyDBEntities())
{
using (var dbContextTransaction = entities.Database.BeginTransaction())
{
try
{
var dataRumah = new ProjekRumah
{
ProjekStatus = 'SpecialScenario',
ProjekName = data.ProjekName, //data passed in from UI
};
entities.ProjekRumah.Add(dataRumah);
entities.SaveChanges(); // the first .SaveChanges to acquire Identity increment
var dataKMDetails = new ProjekKMDetails
{
ProjekID = dataRumah.ProjekID, //identity ID
KMJPBDNo = data.KMJPBDNumber, //data passed in from UI
};
entities.ProjekKMDetails.Add(dataKMDetails);
var table3Details = new Table3
{
ProjekID = dataRumah.ProjekID, //identity ID
Table3Stuff = data.ForTable3Stuff, //data passed in from UI
};
entities.Table3.Add(table3Details );
//..... No .SaveChanges anywhere
//..... more tables, Tables 4, 5 6 etc
//..... No round trips to database
entities.SaveChanges(); //the second and final .SaveChanges()
dbContextTransaction.Commit();
}
catch (Exception ex)
{
dbContextTransaction.Rollback();
}
}
My intent is to be defensive and safe side, is there a syntax to check if Table3 already have row with ProjectID = 7?
To my understanding attempting to delete anything from Table3 will require delete on same corresponding ID in ProjekRumah and ProjekKMDetails and Table4 and so on:
ProjekRumah kmContext = new ProjekRumah {
ProjekID = 7,
ProjekKMDetails = new ProjekKMDetails { ProjekID = 7 },
Table3= new Table3 { ProjekID = 7 }
};
entities.ProjekRumah.Attach(kmContext);
entities.ProjekRumah.Remove(kmContext);
entities.SaveChanges(); //this actually deletes from multiple tables
But at this stage there is no (should be) such record in ProjekRumah table because earlier on: entities.Table3.Add(dataTable3Details) would be illegal and caused rollback.
How do I write code to be on defensive side in case 'Foreign Key Already Exist' happens?
Or such a scenario can never ever 101% to happen?
If possible, I would like to cleanse with EF functions as succinct and as elegant as possible.
PS: I guess I can summarize my question as this:
Suppose an orphan row was found despite Foreign Key constrains (should never happen I believe), but how do I use EF to handle this in a single transaction (preferably with no round trips such as Count, Select, FirstorDefault etc)?

How to get a max number using Breezejs query or is it doable?

While creating a new record using BreezeJs, I want to specify a new number. For example, creating an employee contact, I want to automatically specify the sequence, like 1, 2 ,3 etc.
NextSequence = Max(Sequence) + 1
Well I did following -
getLastMemberCode()
{
var query = new breeze.EntityQuery()
.from('TblMembersMaster')
.select('MembersCode')
.orderByDesc('MembersCode')
.take(1)
.inlineCount();
return createEntityManager()
.then(em => em.executeQuery(query))
.then(queryResult => {
return queryResult.results[0].MembersCode
});
}
And added 1 to the result.

Validate() returns false but it has been saved in the database

I am starting to use grails and I have stumble into a behaviour that I don't understand.
Given this domain class
class Team {
String name
Date since
Date until
static hasMany = [teamMembers:Player]
static constraints = {
name nullable: false, blank: false, unique: true
until nullable: true
until(validator: { val, obj ->
val?.after(obj.since)
})
teamMembers maxSize: 8
//teamMembers size: 0..8
}
}
I wanted to have an integration test that checks that you can't actually have more than 8 players in one team so I wrote a simplified version of this:
void "The team can only have up to 8 players"(){
given:
Player[] players = (1..9).collect {new Player(name: "Foo")}
Team t = new Team(name:"Bar", since: new Date())
expect:
players.each {it.validate()}
t.validate()
when:
players.each {it.save()}
t.save()
players.each {t.addToTeamMembers(it)}
then:
t.validate() == false
t.getTeamMembers().size() == 9
Team.get(t.id).teamMembers.size == 9
Team.first().teamMembers.size == 9
Team.findAll()[0].teamMembers.size == 9
Team.findByName("Bar").teamMembers.size == 9
}
As far as I know, get, find *, etc hit the database. So why does my team fail to validate (expected behaviour) but it has 9 players in the database?
What am I missing?
Notes: Name is not PK for players and I have tested with both constraints, size and maxSize.
Related to this problem, I have found this answer from Peter Ledbrook:
As a summary for this link:
... as soon as you call "save()" on the Team object, it
is attached to the session. Any subsequent changes to that object will
then be persisted to the database including any player you add
If that is right (I haven't really tried), that should fix it:
void "The team can only have up to 8 players"(){
given:
Player[] players = (1..9).collect {new Player(name: "Foo")}
Team t = new Team(name:"Bar", since: new Date())
expect:
players.each {it.validate()}
t.validate()
when:
players.each {t.addToTeamMembers(it)}
t.save()
then:
!t.validate()
}
which means that should only save once the team object (supposing Player has a belongsTo to the Team domain class). Let me know if that works.
Is this a bug? employees.each {t.addToTeamMembers(it)}?
Because you dont have employees variable.
Assuming you want to say players.each {t.addToTeamMembers(it)}:
I think you need to say t.save() after players.each {t.addToTeamMembers(it)} if you want to test to persist.
Your test is not failing because your team size is 9 but you are not actually saving the team.
So try saving before your when

Double records inserted in grails using audit-logging plugin

I have installed the audit-logging plugin into my application. The grails version is 2.1.1 and the plugin version is 1.0.1.
In my Config.groovy class, I have added this
auditLog {
verbose = true // verbosely log all changed values to db
logIds = true // log db-ids of associated objects.
// Note: if you change next 2 properties, you must update your database schema!
tablename = 'audit_logs' // table name for audit logs.
transactional = false
actorClosure = { request, session ->
org.apache.shiro.SecurityUtils.getSubject()?.getPrincipal()
}
and in my domain class I have added this
class Survey {
static auditable = true
static final int NO_RUNNING_SURVERY = 0
static final int RUNNING_SURVERY = 1
static final int CALL_NO_Record_SURVEY = 0
static final int CALL_Record_SURVEY = 1
static final int REALTIME_SURVEY = 0
static final int HISTORICAL_SURVEY = 1
static final int STANDARD_SURVERY = 2
String name
String description
int status
}
when I add, delete and update some thing.
In my audit_logs table, double record inserted against one operation e.g.
If I change the status value from my controller class
def stopSurvey(Long id) {
def survey = Survey.findById(params['stop'])
survey.status = Survey.NO_RUNNING_SURVERY
redirect(action: "list")
}
it inserts two records per call.
#Bertl
I have found the problem,I think, the problem is in plugin. My application uses three databases one is the main database and other two are for other purposes. My databSource is as following.
dataSource.driverClassName = net.sourceforge.jtds.jdbcx.JtdsDataSource
dataSource.dbCreate = update
dataSource.url = jdbc:jtds:sqlserver://localhost:1433/test
dataSource.username = test
dataSource.password = 123
#TEST1
dataSource_TEST1.driverClassName = net.sourceforge.jtds.jdbcx.JtdsDataSource
dataSource_TEST1.readOnly = true
dataSource_TEST1.url = jdbc:jtds:sqlserver://xxx.xxx.xxx.xxx:1433/test1
dataSource_TEST1.username = test1
dataSource_TEST1.password = 123
# TEST2
dataSource_TEST2.driverClassName = net.sourceforge.jtds.jdbcx.JtdsDataSource
dataSource_TEST2.readOnly = true
dataSource_TEST2.url = jdbc:jtds:sqlserver://xxx.xxx.xxxx.xxx:1433/test2
dataSource_TEST2.username = test2
dataSource_TEST2.password = 123
When i use only the test datasource and remove other dataSources, it inserts one record. When i use two datasources then it insert two reocrd in audit logging table.
Same as when i use the three datasources then it insert three record in audit logging.
I need all three databases but it creates the problem. What should i do now?
Didn't see this behaviour here, too. Using this plugin in many projects. Can you please set verbose=false and test again? If the problem happens then also, it means the events might be fired not only once.
A small testapp would be great.
BTW: We use spock tests in the plugins project contained test application (audit-test) to check for how many events are stored in the audit_log table. Therefore I assume an edge case or a specific problem in your app.

Concurrency Issue Grails

I am using this code for updating a row.
SequenceNumber.withNewSession {
def hibSession = sessionFactory.getCurrentSession()
Sql sql = new Sql(hibSession.connection())
def rows = sql.rows("select for update query");
}
in this query I am updating the number initially sequenceNumber is 1200.
and every time this code run then it will b increamented by 1.
and I am running this code 5 times in loop.
but this is not flushing the hibernate session so that every time I am getting the same number 1201.
I have also used
hibSession.clear()
hibSession.flush()
but no success.
If I use following code then its works fine.
SequenceNumber.withNewSession {
Sql sql = new Sql(dataSource)
def rows = sql.rows("select for update query")
}
every time I am getting a new number.
Can anybody tell me what's wrong with above code
Try with Transaction, + flush it on the end, like:
SequenceNumber.withTransaction { TransactionStatus status ->
...
status.flush()
}

Resources