text
stringlengths
1
80.5k
Creating the trigger is fairly straightforward. Salesforce documentation can be lacking, but there are plenty of examples online. For our purposes, we need the trigger to make calls out. Unfortunately this is not allowed directly from the trigger. In order to make calls out, you have to create a separate class to send http requests. You can get to triggers and classes on the "Setup" page by expanding the "Develop" tab under the "Build" section.
public class WidgetOutbound { @future ( callout = true ) public static void widgetSold ( Integer widgetId , Integer widgetContainerId ) { HttpRequest req = new HttpRequest (); HttpResponse res = new HttpResponse (); Http http = new Http (); req . setEndpoint ( ' https: //oursite.com/widget-sold'); req . setMethod ( ' POST ' ); req . setHeader ( ' Content - type ',' application / json ' ); Map < String , Integer > mapBody = new Map < String , Integer >(); mapBody . put ( ' widget_id ' , widgetId ); mapBody .
put ( ' widget_container_id ' , widgetContainerId ); String jsonString = JSON . serialize ( mapBody ); req . setBody ( jsonString ); try { res = http . send ( req ); } catch ( System . CalloutException e ) { System . debug ( ' Callout Error: ' + e ); System . debug ( res . toString ()); } } }
Creating the trigger
Now that we have the outbound class, we can create the trigger that calls it. Keep in mind that triggers can fire on many different events and are not limited to "before update".
trigger update_widget on pba__Widget__c ( before update ) { for ( pba__Widget__c newWidget : Trigger . new ) { pba__Widget__c oldWidget = Trigger . oldMap . get ( newWidget . Id ); Boolean widgetSoldStatusChanged = !( oldWidget . Widget_Sold__c == newWidget . Widget_Sold__c ); if ( widgetSoldStatusChanged && newWidget . Widget_Sold__c ) { System . debug ( ' Widget Trigger: Widget Sold ! ' ); WidgetOutbound . widgetSold ( newWidget . external_ID__c . intValue (), newWidget . RR_Postgres_Account_Id__c .
intValue ()); } } }
Writing Tests
Salesforce requires that any classes and triggers that you write include test cases. These tests are run before deploying from the sandbox to the production site. Some examples of tests follow:
@isTest public class TestWidgetOutbound { public static testMethod void testWidgetSold () { Test . setMock ( HttpCalloutMock . class , new WidgetWebServiceCalloutMock ()); WidgetOutbound . widgetSold ( 1 , 1 ); } public static testMethod void testWidgetUpdateTrigger (){ Test . setMock ( HttpCalloutMock . class , new WidgetWebServiceCalloutMock ()); pba__Widget__c testWidget = new pba__Widget__c ( Name = ' Apex Test Widget ' , Custom_Field__c: ' test data ' , External_ID__c: 1 , Widget_Sold__c: ' No ' );
insert testWidget ; pba__Widget__c testWidget2 = [ SELECT Id FROM pba__Widget__c WHERE Name = ' Apex Test Listing ' LIMIT 1 ]; testListing2 . Widget_Sold__c = ' Sold ' ; update testListing2 ; delete testListing2 ; } } @isTest global class WidgetWebServiceCalloutMock implements HttpCalloutMock { global HTTPResponse respond ( HTTPRequest req ) { // Create a fake response, // Set response values, and // return response. HttpResponse res = new HttpResponse (); res . setHeader ( ' Content - Type ' , '
application / json ' ); res . setBody ( ' { "foo" : "bar" } ' ); res . setStatusCode ( 200 ); return res ; } }
Responding to the Trigger
Handling the responses is easy because they can be handled like any other asynchronous request. With koaBody we can parse the results and store the information accordingly. This can be used to update the database, send emails, or change the business workflow. The basic code follows this structure:
app . post ( '/salesforce/widgetTrigger' , koaBody (), function * () { const details = this . request . body ; //handle details about widget this . status = 200 ; });
Gotchas and other notes
There are a couple things to watch out for when using Salesforce. At times, the Salesforce API can be really slow. Average request times can be up to 3 seconds for simple operations. Below are some other issues that can be addressed if they come up.
Whitelisting Outbound Traffic
A big gotcha of Salesforce is that outbound traffic must be whitelisted. This means that we need to whitelist our site by url so that Salesforce doesn't reject all of our outbound requests. This can be found on the "Setup" page under Administer. Expand the "Security Controls" section and click "Remote Site Settings". There is a wizard to add a "New Remote Site" from this page that will approve any site that you want to send messages to.
Catching Errors with Logs
A good way of ensuring that your application is working properly is by using logs. One trick we found helpful was to have the website login through JSForce/Salesforce as a unique user. That way we could track any changes made by the site. It also allows debug logs to be tracked by user. On the "Setup" page near the bottom on the left is a section for "Monitoring".
If you expand the "Logs" section, you can find the "Debug Logs". By clicking on this, you can see that Salesforce generates many logs even through normal operation.
You can limit what you see and filter it to specific users which will let you see specific errors or problems. This can be useful to figure out where a trigger is failing or what information the trigger is seeing on the fire event.
Conclusion
Hopefully at this point you have a working application that communicates with Salesforce. This can be a tricky process and hopefully I have provided enough resources for you to get this working. Unfortunately, the documentation for Salesforce can be a bit lacking at times, and because of the recent move to "Force.com", many articles are no longer hosted at the same urls.
Other libraries
Judge likens Aftab Ahmed to Walter Mitty during sentencing over threat to David Robinson-Young in pre-election campaign
A judge sentencing a man for threatening to behead a Ukip election candidate has told him he was like the fictional character Walter Mitty.
Aftab Ahmed, 44, made the threat during a heated argument on the phone with David Robinson-Young in the run-up to the general election. The 62-year-old former police officer, who was Ukip’s candidate in Newcastle East, said he was left feeling extremely concerned for his personal safety.
Ahmed, of Heaton, denied a charge of making a threat to kill but was convicted after a trial at Newcastle magistrates court.
Sentencing him to a 12-month community order, Judge Stephen Earl told Ahmed: “I’m still not convinced if I know who you are. A character I can most align you with is Walter Mitty.”
Earl said he was not sure whether Ahmed was the “self-assured entrepreneur” he claimed to be, or a person who made such remarks on the phone to political parties.
But he told Ahmed he did not think the remark had been serious and that it displayed a “lack of mature thought”.
“I am satisfied that the threat that was made from your point of view was a throwaway remark at the end of an agitated phone call,” he said.
Robinson-Young said that in April someone calling himself Mr Khan rang him after receiving a Ukip leaflet. He said he listened patiently for 20 minutes but warned the man he would put the phone down if he did not calm down.
The barrister, who specialises in employment law and discrimination cases, said at the time: “Mr Khan then swore at me saying, ‘you had better f*** off or you will be beheaded next.’”
Robinson-Young added: “This caller was ranting on and on saying that the government supports bombing ‘my Muslim brothers’ abroad.
“If he had let me answer his questions I would have told him that I am the former legal officer for the Race Equality Office in Newcastle-upon-Tyne as well as working on behalf of Muslims many times.”
Following the verdict on Wednesday, Robinson-Young said he felt vindicated after effectively being called a liar by the defendant.
In the light of the murder of soldier Lee Rigbyand Islamic State’s barbarous treatment of its captives, the lawyer said, he was left feeling cold.
“Someone phoning up like that, in the light of what was going on in the world, with what happened to that poor soldier in London, and [suspected Isis beheader] Jihadi John, meant I had to take it seriously,” he said. “Doing what I was doing at the time, knocking on doors throughout the constituency, meant I took it as a real threat.”
Ahmed was sentenced to 100 hours’ unpaid work and told to pay costs of £1,660.
All this dirty air makes me hopeful.
It's often argued that climate change is too slow, too insidious, for humans to take much notice and actually act. Not so when it comes to smog. And as it becomes increasingly clear that smog is having huge economic consequences in cities across the Globe, we can expect the efforts to tackle air quality issues to give very real, substantial impetus to cutting carbon emissions too.
Just take these few examples:
Last year, Paris temporarily banned 50% of cars from its roads and made public transport free . Almost exactly a year later, it is doing the exact same thing again as air pollution spikes to dangerous levels once more . Not only are there significant direct health impacts of such appalling air quality, but between the damage to tourism and the economic costs of banning cars and making buses and trains free, it's not hard to see that the status quo is untenable. (That's why the mayor wants more long-term
action .)
The Guardian also reports that the smog from Europe has carried over to the UK too (that happened last year as well). Meanwhile a recent London bus strike showed how quickly air pollution comes down when you don't burn as much dirty fuel, as long as you can persuade your neighbors to stop burning it too.
And over in China, as a documentary about air pollution goes insanely viral, the country is slashing coal use, shuttering power stations, and the country's Ministry of Transportation has just announced ambitious targets of getting 300,000 alternative fuel buses and taxis (many of them electric) on the road by 2020.
The exciting news is that the tools we need to cut smog and carbon emissions are already here, and they are getting increasing attention from the world's cities. Whether it's bike highways, electric buses, urban forestry, distributed clean energy or radical energy efficiency, as each new project rolls out, there are fewer and fewer excuses for cities not to act.
It sucks that we all have to breathe this dirty air, especially when people are dying, but the alternative could be even worse. When you can't breathe, you have little choice but to act.
Meanwhile, in The Guardian's reporting of Paris' latest smog crisis, I was drawn to this brief quote from Rosa, a concierge sweeping the front of a building near Boulevard Saint Martin as the emergency measures kicked in and the streets were emptied of cars:
“I can breathe.”
Would that we were all so lucky. And just in case you don't think there's anything we can do about it, take a look at Pittsburgh in the 1940s before air quality laws took effect. (Now imagine if they'd had electric buses, teslas and solar panels back then too...)
Open Letter to the Creative Community — Dear Family, Friends and Enemies:
Recently, I responded to a Google-sponsored article in Slate. In my retort, I bitch-slapped Google and its half-bright shill for misrepresenting the truth about piracy and copyright laws.
I won’t bore you by repeating myself, but in summary: Google is the establishment. They are a multibillion-dollar monopoly, and we creatives are just another revenue source. Our work drives their clicks. They don’t care if the click goes to a legitimate site or a pirate site with owners who dabble in human trafficking.
The truth is, they don’t give a shit about free speech, and are the antithesis of their own mantra, “Don’t be evil.”
Not to go all techno-biblical on you, but I’m just a lame, dial-up David, throwing paper pebbles at a 2-terabit army of Robo-Goliaths. So, that’s why I’m disrupting your morning read. Don’t worry, I’m not asking you to donate to a fucking Kickstarter campaign. All I want is to make you aware of what’s happening in the streaming backrooms of the virtual boys club.
Google is in the process of systematically destroying our artistic future, and more importantly, the future of our children and grandchildren. They’re spending tens of millions of dollars each year on eroding creative copyright laws. I believe that if the creative community doesn’t intervene now, and by now, I mean, fucking now — we will be bound to a multigenerational clusterfuck that will take 40 to 50 years to unravel.
Related FTC Launches Task Force to Monitor Big Tech Apple Music Likely Heading to Google Speakers
The last time this happened was in the 1950s, when the tobacco industry spent millions to hide the truth, and convince everyone that smoking cigarettes wasn’t really dangerous to your health.
In other words, Google’s manipulation of public opinion (read: lies) and their proxy campaign for a free Internet and the dissolution of copyright protection (read: criminal tactics) will become so codified in law and will dominate the debate to such a degree that it will be mindlessly accepted on every level. Then, unfortunately, it will be the back half of this century by the time people realize what’s been done, how it was done and that they’ve been thoroughly fucked.
The creative community as we know it will not exist.
Gary Musgrave for Variety
It amazes and terrifies me that essentially all of Google’s fundamental arguments fall into the same template as those used by the Tobacco lobby. And it took five decades to finally reveal the dirty tactics of Big Smoky. We are now just starting to comprehend how those years of lies, extortion and greed created such suffering and death.
Yes, that’s a dramatic comparison (that’s kind of my job), but unfortunately, the relationship is fundamentally accurate. When you’re worth over $200 billion, a couple hundred mil to buy legislation and good PR is an easy check to write. That’s what is happening before our eyes. And the reason why this information may seem startling is that they’re doing it so well; it just looks like business as usual.
Look, I know this sounds alarmist, but if we don’t start ringing some bells, it’s going to be too late. The truth is, I’m not worried about myself. I’m a fat cat with enough things on my plate to feed me till I crash and burn.
I’m worried about our kids. I’ve got a 7-year-old daughter who’s destined to be a live performer (my money’s on bear-wrestling and fire-eating), an 18-year-old son who’s an amazing musician, and a 20-year-old daughter who shines as an actress. They will take on the burden of this. They will wonder how we didn’t see this coming. They will lament that we did nothing to protect their art.
And their kids? Well, they will be told unbelievable tales of the magical days when creatives flourished, and artists were handsomely compensated for their work.
If you’re still reading this and want specifics, try Googling (see, they’ve even managed to become part of our lexicon) a report from the Digital Citizens Alliance called Google & YouTube and Evil Doers: Too Close for Comfort.
And if I’ve pressed your “maybe I do give a shit button,” I urge you to join CreativeFuture. It’s an organization all about advocating for the kind of creative economy we’d like to pass along to our kids. I’m a proud member. There are no dues, no secret handshakes, no cookie-selling requirements. And at some point there may even be free hats.
I sincerely thank you for your valuable time.
(Kurt Sutter is executive producer and showrunner of the FX drama series “Sons of Anarchy.”)
Follow the adventures of the greatest horror writers
'The Spinechillers' is a weekly comic strip relating to the little known story about the time when the world's greatest writers shared a small boarding house to create some of the most loved horror stories of all time.
Small press comic genius Ben Clark is the creative talent behind the strip and will be delivering a freshly drawn adventure each Friday.
Marvel at HP Lovecraft's inspiration for Cthulu, gasp as Ambrose Bierce struggles under the weight of his own creative output, and marvel as Edgar Allan Poe and Sir Arthur Conan Doyle mud wrestle to determine once and for all who is the better horror writer.
"My idea for the comic strip is to take the writers from The Spine Chillers series, and have them all live together in a grotty, 1950s style boarding house, with an indifferent battleaxe of a Landlady called Mrs Parkinson. I thought the boarding house backdrop provided the most scope for stories, conflict and most importantly, jokes. One thing I have to stress is that it is not my intention to belittle or insult these wonderful writers, many of whom are among my greatest heroes. I'll be taking the Mickey,
but in an affectionate way. What I always attempt in my comics is to be silly, and to make people laugh. The characters I am working on are of course not how these men were in real life, but a daft alternate version, which hopefully people will find amusing!"
Ben Clark
UseConveyorSystem Bool IMyCollector/IMyLargeConveyorTurretBase/IMyProductionBlock/IMyReactor/IMyShipDrill/IMyShipToolBase/IMySmallGatlingGun/IMySmallMissileLauncher/IMySmallMissileLauncher
Property Name Result Derived Class Notes
BlockDefinition String IMyCubeBlock Varies by block type.
CheckConnectionAllowed Bool IMyCubeBlock
CubeGrid IMyCubeGrid IMyCubeBlock "Grid, including size. Example: Grid S Large 2959 {100E06F3103FCED}"
DefinitionDisplayNameText String IMyCubeBlock Block’s Name
DiassassembleRatio Float IMyCubeBlock
DisplayNameText String IMyCubeBlock haven’t found anything that seems to set this yet
IsBeingHacked Bool IMyCubeBlock
IsFunctional Bool IMyCubeBlock
IsWorking Bool IMyCubeBlock
Max Vector3I IMyCubeBlock "Returns coordinites, best I can figure is that it involves the space it takes up. Example: [X:1, Y-7, Z:-15]"
Min Vector31 IMyCubeBlock "Returns coordinates, like Max. Example (From same block as max): [X:1, Y:-8, Z:-15]"
NumberInGrid Int IMyCubeBlock You know the number it sticks at the end of the name of a block when you’ve got multiple copies? This is that number.
Orientation Vrage.MyBlockOrientation IMyCubeBlock I’d assume that this is the orientation of the block.
OwnerId Long IMyCubeBlock "Returned 0 for me. I’d assume that since it is a long, it probably is the steam ID of the owner."
Position Vector3I IMyCubeBlock Spatial coordinates relative to the world.
CustomName String IMyTerminalBlock "The name of the block, as seen in the control panel."
CustomNameWithFaction String IMyTerminalBlock