Apex Trigger - Attempting to send an email after an update - email

so I have just finished a degree in computing and have just started industry related employment and wow... we really don't seem to learn much at uni, just the bare basics.
Anyway, I am learning Apex and attempting to write my first trigger. The online tutorials are pretty unforgiving and I find that they seem to all miss out what my brain is lacking.
I am writing a trigger to automatically send an email to a specified address, the sending the email part is fine however I want to send in the email what has been changed and read as to whether it anything has been changed. What I have so far is as follows:
trigger Test1 on Account (after update) {
if(Trigger.isUpdate) {
//Commit current transaction, reserver email capacity
Messaging.reserveSingleEmailCapacity(1);
//Create an email message object
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<Messaging.SendEmailResult> results = new list<Messaging.SendEmailResult>();
//hold email address
String[] toAddresses = new String[] {'example#example.com'};
//Assign new address string
mail.setToAddresses(toAddresses);
//specify return ad (assuming as being sent from server)
mail.setReplyTo('pwitherby#gmail.com');
//sender name
mail.setSenderDisplayName('Mr Apex Tester');
//Subject Specification
mail.setSubject('Subjected to Learning');
//And... the content
mail.setPlainTextBody('You have just changed sumek... this really what you want....?')
if (!results.get(0).isSuccess())
System.debug('That didnt really work did it? Reason: ' + results.get(0).getErrors()[0].getMessage());
}
}
So my main questions that I cant find an answer for:
Will this work at current? so will this send this email if anything in the schema gets altered/updated?
I want to put in the email body what has been altered and what it has been changed to i.e "you have changed " + whatsChanged + " to " + telephoneNumber.
How do I listen for changes or is it already doing that?
Am I writing this to a decent standard or is it just messy code!
Sorry to waffle, it is my biggest downfall however I struggle to augment my questions without it!

You don't need to activate a trigger just writing it is enough.
You can access the changed new values Through Trigger.new (and Trigger.old for old values)
For Trigger documentation refer here
Maybe a workflow is more suitable to what you are trying to do.
And finally don't worry too much from the start about standard of the code (or beauty), it makes difference only when your code gets big anyway.

Related

I'm wanting to create a separate file of every member who joins the server and then be able to chose them randomly for a 'winner' command sorta thing

So I am using discord.js or Visual studio code or whatever. and I've made a random hug command. And I would like to be able to have it so that the one that gets hugged doesn't get # and it's just their name. I've successfully made a command similar to it, but i don't want to have to keep adding in names manually and theres no promise that the member won't change their name so it's not very reliable.
So I guess what's in my mind is having a file that automatically updates with users leaving or joining or changing their names and then to be able to call on them randomly without #ing them.
So does anybody know how to do this and how i can call on them?
I've done it with the #, and now im at where I manually write in every member's name but I know that is going to end up tedious and their name might change and I don't want to have to worry about them changing their name.
case 'randhug':
var user = message.guild.members.random();
let dismember = ["Klemon", "Second sofira", "CloudBot"]
let disresults = Math.floor((Math.random() * dismember.length));
message.channel.send(`${message.author} SURPRISE huggies you, ${dismember[disresults]}!!!!!`);
if (message.author.bot) return;
break;
The code I have now works, but isn't reliable in the sense that things change.
It sounds like you might find the tag or username properties of a User very valuable in this situation.
User.tag would return Username#1234.
User.username would return Username.
const member = message.guild.members.random();
message.channel.send(`${message.author} surprise huggies you, **${member.user.username}**!`)
.catch(console.error);

Reading an SB-Messaging Send Port properties using the Microsoft.BizTalk.ExplorerOM makes a breaking change

I am working on a PowerShell script making use of the Microsoft.BizTalk.ExplorerOM to dynamically update the SB-Messaging SAS key for BizTalk Receive Locations and Send Ports. This is to enable us to roll the SAS keys for our Service Bus queues, and update BizTalk with the new keys as painlessly as possible.
I have this working correctly for Receive Locations, but Send Ports are giving me a different issue.
As soon as I read the PrimaryTransport properties of the Send Port, it seems that some change is made under the covers, that then prevents SaveChanges from working, instead throwing an "Invalid or malformed XML data exception".
This is compared to the the ReceiveLocation, where I can read any of its properties, and then SaveChanges successfully.
Note that in both of this cases, no changes have been made by me. I am simply doing a Read, and then a Save.
Can anyone offer any advice as to what could be causing the issue, and any possible solutions to try?
Had this very same issue, when using Powershell to replace values in ServiceBus ReceiveLocations & SendPorts.
The problem is with the none valid xml symbols in the TransportTypeData, which are converted when the script reads them out in the PS cmd.
All none valid xml symbols (such as the one occuring for Namespace value, ) need to be converted to amp, and if I'm not mistaken even double amp:ed.
Here's an example article showing examples on what I mean by "double amp:ed":
How do I escape ampersands in XML so they are rendered as entities in HTML?
Hope this make sense, and if not, then let me know and I'll give it another go.
Just tried doing this from C#, seems to work ok:
var root = new Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer() { ConnectionString = "Data Source=(local);Initial Catalog=BizTalkMgmtDb;Integrated Security=SSPI;" };
var sendPort = root.SendPorts["xxxx.ServiceBusQueue"];
System.Diagnostics.Trace.TraceInformation(sendPort.PrimaryTransport.TransportTypeData);
sendPort .PrimaryTransport.TransportTypeData = sendPort.PrimaryTransport.TransportTypeData.Replace("RootManageSharedAccessKey", "MySharedAccessKey");
root.SaveChanges();

Automatically send email about editing google spreadsheet

I'm working on a rather simple script which should handle new values in the spreadsheet and then send emails to specified addresses. And I faced with the problem. My code is listed below:
function onEdit(e) {
//part of the code for checking e.range to process only updated values
sendEmail();
}
function sendEmail() {
// arguments are missed only for demo
GmailApp.sendEmail();
}
While I'm using "simple trigger", my function "sendEmail()" works only if I start it from script editor. I allowed sending emails on behalf of my at first time and then function works fine. But if I'm changing the value in the spreadsheet - function "onEdit(e)" processes new data but function "sendEmail()" does nothing.
I partly solved this problem by using project's triggers from "current project's triggers" menu. In that case, function "sendEmail()" works properly, but I have no access to the information about update.
For my purposes I could use just second way and find new values "manually" every time, but I wish to optimize this work.
So, my questions are:
Is the process I described above proper or I made a mistake
anywhere?
If process proper, is where a way to combine both cases?
Thanks!
You correctly understood that (as the docs say) simple triggers cannot send an email, because they run without authorization. An installable trigger, created via Resources menu, can: it has the same rights as the user who created the trigger. If it is set to fire on edit, it will get the same type of event object as a simple trigger does.
So, a minimal example would be like this, set to run "on edit":
function sendMail(e) {
MailApp.sendEmail('user#gmail.com', 'sheet edited', JSON.stringify(e));
}
It emails the whole event object in JSON format.
Aside: if your script only needs to send email but not read it, use MailApp instead of GmailApp to keep the scope of permissions more narrow.

TYPO3 : no updated newsletter with direct_mail and scheduler

This is my 1st question on this forum... So, please, be indulgent !
I'm using TYPO3 4.7.11 (PHP 5.3.3) with extension direct_mail 3.1.1 for the intranet site of a non-profit firm.
My problem (maybe connected to Bug #51583 : http://forge.typo3.org/issues/51583) is that, after numerous tests and attempts, it seems impossible to have an updated version of a page saved as draft for newsletter in an automatic scheduler driven way : the same newsletter is produced with the same informations that were already there on the day it was first created and saved.
The specific page used for newsletter includes a content element 'Menu/Sitemap' with 'Recently updated pages' as 'Menu type'. It has been saved as 'draft (for recurring sendings)' in Direct Mail.
The scheduler contains these 2 tasks with recurring type :
- Direct Mail: Create Mail from Draft (direct_mail)
- Direct Mail: Mailing Queue (direct_mail)
Note : the manual way is fully functional and the newsletter produced is really updated. Same with option "Testmail - Simple" !
So, my problem seems to be linked to the automatic scheduled mailing ! It looks as if the newsletter draft has turned into a freezed snapshot of a specific moment and that Typo3 is unable to update/recalculate this page when invoked in scheduler mode.
On the web, I saw reported problems that could be related like "When mails get sent via the scheduler the same subject is used for all sendings ( https://review.typo3.org/21313 )" and "Adding hooks when sending direct mails via scheduler ( forge.typo3.org/issues/48994 )", but these issues seem to be fixed with direct_mail 3.1.1 version.
I made these observations and, in my opinion, there is some relevancy :
1.There is no domain proposed in the 'Domain of internal links' drop-down list in 'Set default values for mail content fetching options' in Direct Mailer, and yet I have a single record in sys_domain table with a domain name (with no protocol and no final slash). Is there a reason why this record is not considered good, or isn't it the right table ? (uid=3, pid, tstamp, crdate, cruser_id, hidden, sorting, prepend_params and forced=0, redirectHttpStatusCode=301, domain_name=site.subdomain.domain, redirectTo=)
2.In the Typo 3 Log, I get this systematic error message for user _cli_scheduler#LIVE :
Core: Error handler (BE): PHP Warning: Invalid argument supplied for
foreach() in
...typo3conf/ext/direct_mail/Classes/Scheduler/MailFromDraft.php line
125.
The concerned part of MailFromDraft.php is this function : initializeHookObjects
...
/*
* Initializes hook objects for this class
*
* #return void
*/
function initializeHookObjects() {
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['direct_mail']['mailFromDraft'] as $hookObj) {
$hookObjectInstance = t3lib_div::getUserObj($hookObj);
if (is_object($hookObjectInstance) && ($hookObjectInstance instanceof x_directmail_Scheduler_MailFromDraftHook)) {
$this->hookObjects[] = $hookObjectInstance;
}
}
}
...
I'm not sure of understanding very clearly the origin and the use of the hook Object... (in spite of this interesting article by Robert Lemke : typo3.org/documentation/article/how-to-use-existing-hooks-in-your-own-extension/ )
3.Nothing like the apparently requested GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['direct_mail']['mailFromDraft'] seems to exist in TYPO3_CONF_VARS (Global configuration).
Can anybody give me an advice or a clue about what's going on and why I can't get a weekly updated newsletter with the scheduler ? I feel a bit confused !
Thanks in advance for any suggestion or solution (if a miracle is possible).
Greetings.
P-H SILLIAU
I've read about this issue before, but couldn't remember where.
Googling "direct_mail draft (for recurring sendings)" helped.
Try this bug: http://forge.typo3.org/issues/4421
User Markus says:
Things work fine, when you set a domain-record in your system and
select it in the direct_mail settings!
If you don't have a domain-record and specify it in the direct_mail
setup you're able to send normal newsletters, but if you try the
draft-functionality it won't work because the getUrlBase function in
class.tx_directmail_static.php returns an unsuable URL to the System
so it can't use the fetchHTML($file) and quits - therefore not
replacing the old draft contents created when starting the first time.
I don't really get why this works the first time you set up the draft
though....
So setting up the domain-record is a work-around that works.
I hope it does!
Probably, you will find more related topics.
Else, workarounds would be
re-considering the task. As it's a NPO intranet, maybe requirements are not that required suddenly, if asked again :-)
setting up a custom notification tool that only does that precise job.
To put an end to this problem, after many attempts (and informations gleaned from the internet), here is the solution we finally used in our specific case to make the newsletter work :
1st. We created a record in table sys_domain. This was a recurrent instruction in the manual and the forums, and it was IMHO legitimate.
Important : note that the redirectTo field had to remain empty, due to global malfunction of the site if filled (whatever we put in it like /, /var/www/sitename, ...)
2nd. All images, CSS, JS included in template had to be hardcoded (i.e. http ://site/fileamin/images/xxx.png for instance). If we didn't do that, the result would have been an abort in the production of the newletter : Not Found... Maybe, by digging a bit deeper, should we be able to find a parameter we forgot or neglected in some way to solve this issue...
3rd. In the newsletter template TS setup, we added these 2 parameters :
mod.web_modules.dmail.use_domain=[uid of sys-domain]
config.absRefPrefix = / (in order to get rid of PHP DOCUMENT_ROOT (or TYPO3_DOCUMENT_ROOT ?) otherwise wrongly present in all generated links.)
The result is now a well dynamically-generated newsletter, the date is OK, all links are correct and realUrl-compliant (no ../index.php?id=nnn) .... and you know what ?... We're happy ! :-)
Hope it will help !
Many thanks to everybody who answered (Markus, Urs...) or even thought of a possible solution...
P-H Silliau

Magento Automatically send tracking email

OK, been searching this everywhere, and can't come up with anything... we are externally populating tracking numbers in Magento Community 1.7.0.2 via a sync program from Dydacomp's Mail order Manager software... - it closes the order in Magento and adds a tracking number, but does not trigger the send tracking email function in mage. - I have researched, and seen that there are observers, etc. which appear maybe to be able to do this, but after 20 hours scouring every blog I can find, etc. cannot come up with anything that works!
This link seems to be REALLY in the right direction... but where to put this block of code? I've tried putting it in all kinds of places and none works:
Programmaticly send email when shipping tracking number is set
Any help would be tremendously appreciated.
I developed something similar. I created a module activated by cron (once a day) that checks the last orders that have 'delivered' (complete status).
To run a function in your cron magento module, add to your config.xml
<crontab>
<jobs>
<myModule_myFunction>
<schedule><cron_expr>*/60 * * * *</cron_expr></schedule>
<run><model>emailtracker/cron::myFunction</model></run>
</myModule_myFunction>
</jobs>
</crontab>
For the order to have supplies you can use the following code snippet
$orders = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', 'complete')
->addAttributeToFilter('created_at', array('gteq' => $dataForFilter));
Note that the collection of orders that I created, I make filter by date to avoid retrieving all orders already made​​.
With my collection of recent and complete orders that are possible candidates to receive a tracking email delivery, I can actually work with the orders that are important.
I created a foreach to run in my collection and within that loop, retrieve the tracking number.
foreach($orders as $order) {
$trackings = Mage::getResourceModel('sales/order_shipment_track_collection')
->setOrderFilter($order)
->getData();
for($i=0;$i<count($trackings);$i++) {
$trackingNumber = $trackings[$i]['track_number'];
//Make your php magic here
}
}
From this point, you can work this information the way you want. You can create a function that checks the status of tracking number via API and its delivery service sends an email, or you can imagine.
Important: Remember to check if your magento cron is active.
Note: I did it in Magento 1.6.1.0