<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roger Mitchell on Medium]]></title>
        <description><![CDATA[Stories by Roger Mitchell on Medium]]></description>
        <link>https://medium.com/@RogerMitchell?source=rss-56f6ed5904f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZFftjP-jLQ4vpCIQVdh9zA.jpeg</url>
            <title>Stories by Roger Mitchell on Medium</title>
            <link>https://medium.com/@RogerMitchell?source=rss-56f6ed5904f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:59:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@RogerMitchell/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Svelte with Lightning Web Components]]></title>
            <link>https://medium.com/@RogerMitchell/using-svelte-with-lightning-web-components-e7e230e76772?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7e230e76772</guid>
            <category><![CDATA[pizza]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[lightning-web-component]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 20:56:31 GMT</pubDate>
            <atom:updated>2020-04-16T15:59:40.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Svelte with Lightning Web Components (LWC)</h3><p>I’ve been hearing about <a href="https://svelte.dev/">Svelte</a> on a few podcasts recently (notably on <a href="https://syntax.fm/">Syntax.fm</a>) and saw <a href="https://medium.com/u/69a16563861c">Matt Lacey</a> <a href="https://twitter.com/LaceySnr/status/1247473860502405120">tweet</a> about the pleasing nature of <a href="https://svelte.dev/tutorial/basics">their tutorial docs</a>.</p><p><strong><em>So, like any hipster front end framework nerd, I asked is it worth using Svelte in production after a quick tutorial? </em>🤓</strong></p><h3><strong>Why use Svelte? There’s already React, Vue, LWC…</strong></h3><p>Svelte is on par with other frameworks; it supports composition, data binding, lifecycle hooks, eventing, etc.</p><p>But unlike the other popular frameworks, <a href="https://svelte.dev/blog/virtual-dom-is-pure-overhead"><strong>Svelte doesn’t use a virtual/shadow DOM</strong></a> to compare what the browser has painted to the next render. Instead, <strong>Svelte applications are compiled</strong> and shipped as a minimal bundle of vanilla JavaScript.</p><p>The result is <strong>faster applications</strong> because the <strong>client’s browser has less work</strong>, and there’s <a href="https://svelte.dev/blog/write-less-code"><strong>no framework bloat</strong></a> shipped with the app.</p><p>Also, if you care about <a href="https://svelte.dev/tutorial/animate"><strong>animations</strong></a> and storing application state outside of components in a <a href="https://svelte.dev/blog/svelte-3-rethinking-reactivity"><strong>Redux like store</strong></a>, Svelte has built in functionality to support that, and with way less boilerplate.</p><h3>You convinced me that Svelte is rad, but why use it within LWC?</h3><p>Here are a few cases where it makes sense to rely on a third party framework for a majority of your application:</p><ul><li>You’re building a custom application that doesn’t (need to) rely on <a href="https://developer.salesforce.com/docs/component-library/overview/components">base components offered by LWC</a></li><li>You’re building or already have built an app, and you want the experience to be identical regardless of whether the user is inside Salesforce</li><li><strong>You’re a purist for simple code for your (not so) simple apps</strong></li></ul><p><a href="https://developer.salesforce.com/docs/component-library/documentation/en/lwc">LWC</a> is great and it’s a huge step forward compared to the awkwardness of <a href="https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/">Aura</a>; it also relies on tons of boilerplate that adds negative value to the developer experience.</p><h4><strong>Example 1: Data Binding</strong></h4><p>We’re building a simple form with a few inputs. Let’s see how this looks in LWC.</p><pre>// form.js in LWC<br>export default class Form extends LightningElement {<br>  <a href="http://twitter.com/track">@track</a> name;<br>  <a href="http://twitter.com/track">@track</a> customField;</pre><pre>  handleChange(event) {<br>    switch(event.target.name) {<br>      case &#39;Name&#39;:<br>        this.name = event.target.value;<br>        break;<br>      case &#39;Custom_Field__c&#39;:<br>        this.customField = event.target.value;<br>        break;<br>    }<br>  }<br>}</pre><p><strong>Holy wow! 🐄 🐄 🐄 </strong>That’s a <strong>ton of lines</strong> to bind some input values. Let’s see how this looks in Svelte.</p><pre>// Form.svelte<br>&lt;script&gt;<br>  let name = &#39;&#39;;<br>  let customField = &#39;&#39;;<br>&lt;/script&gt;</pre><pre>&lt;input bind:value={name}&gt;<br>&lt;input bind:value={customField}&gt;</pre><p>Svelte’s entire component (logic + markup) has less lines of code than the handleChange function from the LWC component. <strong>🥜 🥜 🥜 Nuts!</strong></p><h4>Example 2: Expressions</h4><p>We’re building a “Customer 360 experience” app (<em>what does that even mean?!</em>) and we need to conditionally render some markup based on whether we have data.</p><p>LWC ditches expressions in markup and <a href="http://🥜 🥜 �">uses getter methods</a> 🙌 that are more functional than the wackadoo Aura days. <br>{!v.data.length &gt; 0 &amp;amp;&amp;amp; v.isThisFun} = 🙅‍♂️🙅‍♀️</p><p>So in LWC, we’d throw a getter in there to figure out whether to show stuff.</p><pre>// customer360.html in LWC<br>&lt;template&gt;<br>  &lt;div if:true={hasData}&gt;👩‍💻👨‍💻👩‍💻👨‍💻👩‍💻👨‍💻👩‍💻👨‍💻&lt;/div&gt;<br>  &lt;div if:false={hasData}&gt;🤷‍♀️🤷‍♂️🤷‍♀️🤷‍♂️🤷‍♀️🤷‍♂️🤷‍♀️🤷‍♂️&lt;/div&gt;<br>&lt;/template&gt;</pre><pre>// customer360.js in LWC<br>export default class Customer360 extends LightningElement {<br>  <a href="http://twitter.com/track">@track</a> data = [];</pre><pre>get hasData() {<br>    return this.data.length &gt; 0;<br>  }<br>}</pre><p>Svelte uses expressions in markup in a concise manner with a little framework specific syntax.</p><pre>// Customer360.svelte<br>&lt;script&gt;<br>  let data = [];<br>&lt;/script&gt;</pre><pre>{#if data.length &gt; 0}<br>  &lt;div&gt;👩‍💻👨‍💻👩‍💻👨‍💻👩‍💻👨‍💻👩‍💻👨‍💻&lt;/div&gt;<br>{:else}<br>  &lt;div&gt;🤷‍♀️🤷‍♂️🤷‍♀️🤷‍♂️🤷‍♀️🤷‍♂️🤷‍♀️🤷‍♂️&lt;/div&gt;<br>{/if}</pre><p>Do we need a function to tell us that data has length greater than 0? Maybe, maybe not; I lean towards not.</p><h3>Let’s see Svelte inside LWC</h3><p>Unlike our previous example #Customer360 #SocialEnterprise app, we have an executive that refuses to use Salesforce unless they can see a list of contacts and click a link to change a name to 🍕🍕 (<em>it’s a very serious enterprise</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gORcIXIArFFnC6ww7Y0KhA.gif" /><figcaption>Josh and Jane just got 🍕🍕</figcaption></figure><p>Because of our executive’s insanity, we implemented this app using Svelte, instead of exclusively using standard LWC and Aura; as a result, we were able to learn a few patterns for how Svelte can interact within LWC.</p><h4><strong>Mounting in the DOM</strong></h4><p><strong>Locker Service is a ruthless dictator</strong> that keeps us from using the new Component({ target: document.querySelector(&#39;div#app&#39;), props: {}) pattern for injecting Svelte. 👺</p><p>A little workaround allows our <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/src/main.js">Svelte component</a> to add a function called mount onto window, and our <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/force-app/main/default/lwc/svelte/svelte.js#L18">LWC component</a> calls that along with our desired entry point. 🎉</p><pre>/*** svelte.js in LWC ***/<br>Promise.all([<br>  loadScript(this, svelteApp + &#39;/bundle.js&#39;),<br>  loadStyle(this, svelteApp + &#39;/bundle.css&#39;)<br>])<br>.then(() =&gt; {<br>  mount(this.template.querySelector(&#39;div[data-id=&quot;app&quot;]&#39;), {<br>    name: &#39;🍕🍕🍕🍕🍕&#39;,<br>    getContacts,<br>    updateContactToPizza<br>  });<br>})</pre><pre><br>/*** main.js in Svelte (pre-compilation) ***/<br>import App from &#39;./App.svelte&#39;;</pre><pre>window.mount = (target = document.body, props = {}) =&gt; {<br> return new App({target, props});<br>}</pre><pre>export default window.mount();</pre><h4><strong>Calling Apex</strong></h4><p>Would we use Svelte to do anything aside from CRUD apps? <strong><em>Of course not!</em></strong> 🤦‍♀ Thankfully we can pass <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/force-app/main/default/lwc/svelte/svelte.js#L3">imported references</a> to <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/force-app/main/default/lwc/svelte/svelte.js#L25">Apex methods as props</a> down to <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/src/App.svelte#L11">our App component</a>. 📦 ⬇️</p><pre>/*** svelte.js in LWC ***/<br>import getContacts from &#39;<a href="http://twitter.com/salesforce/apex">@salesforce/apex</a>/SvelteController.getContacts&#39;;<br>import updateContactToPizza from &#39;<a href="http://twitter.com/salesforce/apex">@salesforce/apex</a>/SvelteController.updateContactToPizza&#39;;</pre><pre>...</pre><pre>mount(this.template.querySelector(&#39;div[data-id=&quot;app&quot;]&#39;), {<br>  name: &#39;🍕🍕🍕🍕🍕&#39;,<br>  getContacts,<br>  updateContactToPizza<br>});<br></pre><pre>/*** App.svelte (pre-compilation) ***/<br>// props<br>export let getContacts; // public<br>let contacts = []; // private</pre><pre>// some function to handle clicks<br>let handleClick = event =&gt; {<br>  getContacts()<br>    .then(result =&gt; {<br>      contacts = result;<br>    })<br>    .catch(error =&gt; console.error(error))<br>}</pre><pre>// functions<br>let handleClick = event =&gt; {<br>  getContacts()<br>    .then(result =&gt; {<br>      contacts = result;</pre><pre>// we can also update the store&#39;s version of this too!<br>      storeContacts.set(result);<br>    })<br>    .catch(error =&gt; console.error(error))<br>}</pre><p>Since LWC returns a promise when we call an Apex method, we’re able to <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/src/App.svelte#L17">handle the results and errors</a> in the same way that we would inside LWC. 💪</p><h4>Component Events</h4><p>Locker Service is <strong>still a ruthless dictator</strong> (<em>that protects us and our apps from evil!</em>) and blocks the neat way that <a href="https://svelte.dev/tutorial/component-events">Svelte’s component events</a> work. 🦹‍♂️</p><p>But like all ruthless dictators, there’s a way around their wrath. 🐈</p><p>At the highest level component, we can define a <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/src/App.svelte#L48">function that acts as a broker</a> to pass events to the appropriate functions, and <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/src/App.svelte#L65">pass this function down</a> to <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/src/ContactList.svelte#L4">child components as a prop</a>. Child components can <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/src/ContactList.svelte#L11">call this function</a> and pass an event payload for processing.</p><pre>/*** App.svelte (pre-compilation) ***/<br>let eventBroker = event =&gt; {<br>  switch(event.name) {<br>   case &#39;changeNameToPizza&#39;: <br>    handleNameToPizza(event);<br>    break;<br>  }<br>}</pre><pre>&lt;ContactList {eventBroker} /&gt;</pre><pre>/*** ContactList.svelte (pre-compilation) ***/<br>export let eventBroker;</pre><pre>function handleClick(event) {<br>  eventBroker({<br>    name: &#39;changeNameToPizza&#39;,<br>    detail: {<br>      id: event.target.id<br>    }<br>  })<br>}</pre><pre>&lt;li&gt;<br>  {contact.Name} • &lt;a id={contact.Id} on:click={handleClick}&gt;Click to change name to 🍕&lt;/a&gt;<br>&lt;/li&gt;</pre><p>It’s definitely not as clean as Svelte’s implementation, but it allows for passing an event {name: &#39;someString&#39;, detail: { ... }} to somewhere else for processing in a similar fashion. It’s still a bit disappointing. 😢</p><h4>Dev Tooling</h4><p>Within a normal SFDX project, we can create a subfolder to manage our Svelte application and <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/rollup.config.js">use our rollup config</a> to move the compiled bundle into <a href="https://github.com/rogeramitchell/lwc-svelte/blob/master/svelte/rollup.config.js#L15">a static resource</a>. It’s essentially the same workflow you may be used to with React, Vue, and whatever other fun flavored frameworks you’re using.🍨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*7G1L45DYofY0wHgORc7YMQ.png" /><figcaption>Tossing 🐑🐑🐑 over walls is fun!</figcaption></figure><h3>Still with me? How do we wrap this up? 🎀</h3><p>In many ways, LWC is a better tool as a front end developer in Salesforce based on all of the base components, and the benefits that Locker Service provides. But LWC is also verbose in ways that it doesn’t need to be, which is where frameworks like Svelte make it much nicer to dev apps.</p><p><strong>TLDR: Svelte is great, Locker Service is (a necessary) evil, and you can use Svelte in LWC… but you won’t.</strong></p><p>Have you played around with Svelte? How about LWC? What about Svelte in LWC with Lighting Out mounted in a Sites page? 🤮</p><p>Let me know in the comments below or on <a href="https://twitter.com/rogermitchell">Twitter</a>, it’ll be a party!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7e230e76772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux: Performance Comparison Between Process Builder and Apex Triggers]]></title>
            <link>https://medium.com/@RogerMitchell/redux-performance-comparison-between-process-builder-and-apex-triggers-f30ae6904267?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f30ae6904267</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-productivity]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 21:41:46 GMT</pubDate>
            <atom:updated>2018-08-01T21:41:46.126Z</atom:updated>
            <content:encoded><![CDATA[<p>At the end of 2016, I posted about the performance differences between Process Builder and Apex Triggers on single record and bulk transactions (it’s a good read, <a href="https://medium.com/@RogerMitchell/performance-comparison-between-process-builder-and-apex-triggers-e4a1f455f9c1">check it out here</a>).</p><p>Since it’s been over 18 months and Salesforce has been improving the platform with every release, can we prove it?</p><p>As a recap, our test scenario was somewhat contrived… when an Account is inserted with a name that starts with “Test”, Salesforce must create a new Contact and new Opportunity. For that Opportunity, there must exist 4 Opportunity Products.</p><p>With the same configuration (2 processes vs 1 trigger), the results are impressive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*KtyiWuPirOCHS3xAe7q5hg.png" /><figcaption>TLDR: Process Builder gained efficiencies somewhere, and it’s nearly just as fast as Apex.</figcaption></figure><p><strong><em>Process Builder</em></strong> was much slower than an Apex trigger back in December 2016, but <strong><em>has improved massively</em></strong> as of August 2018. If you’re interested in looking at the comparison data, check out <a href="https://docs.google.com/spreadsheets/d/1Q7fmBXQuuJ_LlKL1ZAR1pdFTdjGnB6gyPXfrXlymfRI/edit?usp=sharing">this Google Sheet</a>.</p><p>While Apex is still faster than Process Builder, the performance benefits may not be realized if your team either lacks development resources, or needs to rely on outside consulting partners. Feel free to tweet <a href="https://twitter.com/RogerMitchell">@RogerMitchell</a>, leave a comment below, or silently forward this along to your admin and dev colleagues.</p><p><strong>Shameless plug… </strong>if you’re interested in working with a consulting partner that appreciates when to use config and code that will scale for your organization, you may want to check out <a href="https://www.dodgelabs.com/">Dodge Labs</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f30ae6904267" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Admin Configurable UIs with Salesforce and React]]></title>
            <link>https://medium.com/@RogerMitchell/building-admin-configurable-uis-with-salesforce-and-react-88578bcc4217?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/88578bcc4217</guid>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Sun, 26 Mar 2017 21:59:53 GMT</pubDate>
            <atom:updated>2017-03-26T21:59:53.577Z</atom:updated>
            <content:encoded><![CDATA[<p>Custom developed UIs can be a daunting thing to introduce to a client’s Salesforce org if the team does not have development resources available to make changes in the future. This can be mitigated upfront by building <strong>configurable UIs</strong> that allow an admin to update the view layer and its components using <strong>clicks not code</strong>. In this example, we’ll check out a Visualforce page that serves up a React app, and how this React app respects <strong>configurable metadata</strong> within the org.</p><p>Here’s a quick demo video that shows this from the admin’s perspective:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsJjwvq-a5Iw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsJjwvq-a5Iw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsJjwvq-a5Iw%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa46be064e0ce2fff73a2dc993ed9db2/href">https://medium.com/media/fa46be064e0ce2fff73a2dc993ed9db2/href</a></iframe><p>Our app leverages the standard <strong>field set</strong> and <strong>custom metadata type</strong> options within the Salesforce setup menu, and combines these with the <a href="https://github.com/rogeramitchell/FieldSetReactor"><strong>Field Set Reactor</strong> repo</a> to describe the metadata in context of the current user. Let’s dive in and see how these three components work alongside our client-side React app to create an admin configurable UI.</p><h4>Custom Metadata Types: An Alternative to Custom Settings</h4><p>Custom metadata types were released in Summer ’15 as an alternative to custom settings. With these, developers and administrators can deploy the data in each custom metadata type alongside change sets, thus decoupling the potential for data discrepancies between environments as part of releases and sandbox refreshes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cd9SU6xP9_LfvC5kVa9jCQ.png" /><figcaption>A custom metadata type record for the Account Header</figcaption></figure><p>Within the app, we use custom metadata types to define sections of the UI, how these sections interact, and the object/fields that comprise that section. Each record’s <strong>DeveloperName</strong> allows us to reference this section within our React app code. The rest of these fields allow admins to control aspects of the UI:</p><ul><li><strong>Active__c</strong> checkbox allows control of whether to display this section</li><li><strong>Section_Order__c</strong> defines how sections appear relative to one another</li><li><strong>Object_Name__c</strong> specifies the object to which the field set belongs</li><li><strong>Field_Set_Name__c</strong> binds a field set to this particular section</li></ul><h4>Field Sets: Tried and True</h4><p>Field sets have been around for a while, and are quite easy to implement within a Visualforce page using standard components like &lt;apex:repeat&gt;. Another use for field sets is within Apex to control fields used in a query or clone operation. In our app, field sets allow the admin to define the set of fields that should appear in a given section on the UI, and ensures the Apex controller includes those fields when serving data to the UI.</p><p>Our use of field sets is to allow the admin to control which fields should appear on a per object basis, and for the developer to use these for describing the field attributes and accessibility for the current <br>user.</p><h4>Field Set Reactor: A Utility to Help SPA Developers</h4><p>Once we grab the custom metadata types for the current page along with the field sets, we need to describe the fields in context of the current user’s access to ensure our UI is flexible and matches the current config. <a href="https://github.com/rogeramitchell/FieldSetReactor">Field Set Reactor</a> has a method that returns a collection of the <strong>FieldDetails</strong> inner class, which does everything from provide the API name and data type, to the user’s read/edit access for the field and the label the user sees in standard pages.</p><p>For each field set that appears in the custom metadata types for our page, we get a collection of <strong>FieldDetails</strong> and put this into a map with a key as the custom metadata type’s <strong>DeveloperName</strong>.</p><pre><a href="http://twitter.com/RemoteAction">@RemoteAction</a><br>public static Map&lt;String, List&lt;FieldSetReactor.FieldDetails&gt;&gt; getFieldDetails(List&lt;Dynamic_Page_Mapping__mdt&gt; pageMapping)<br>{<br>Map&lt;String, List&lt;FieldSetReactor.FieldDetails&gt;&gt; sectionFieldDetails = new Map&lt;String, List&lt;FieldSetReactor.FieldDetails&gt;&gt;();<br> <br> for(Dynamic_Page_Mapping__mdt pageMap : pageMapping)<br> {<br> List&lt;FieldSetReactor.FieldDetails&gt; fieldDetails = FieldSetReactor.getFieldDetails(pageMap.Field_Set_Name__c, pageMap.Object_Name__c);<br> sectionFieldDetails.put(pageMap.Field_Set_Name__c, fieldDetails);<br> }<br> <br> return sectionFieldDetails;<br>}</pre><h4>Bundling Together in a Single Package</h4><p>All of this logic is returned to the Visualforce page as a bundle called <strong>AccountManagementState</strong>, defined within the <strong>AccountManagementController</strong>. This bundle represents not only the sections that comprise the Visualforce page, but also the data that we will pass to each of the sections as props. When the page loads, JavaScript remoting calls the <strong>getInitialState</strong> method in <strong>AccountManagementController</strong>, and then the callback parses the response into the React state.</p><p>Here’s what each component of the return value from <strong>getInitialState</strong>:</p><ul><li><strong>sectionMap</strong> a collection of our custom metadata type</li><li><strong>fieldMap</strong> a map where each key is the custom metadata type records’ <strong>DeveloperName</strong>, and value is a collection of <strong>FieldDetails</strong> (from previous section)</li><li><strong>account</strong> the Account record with its fields</li><li><strong>contacts</strong> a collection of Contacts related to the <strong>account</strong></li><li><strong>opps</strong> a collection of Opportunities related to the <strong>account</strong></li></ul><h4>From the Front End: Integrating with React</h4><p>Our utility modules and React components exist in <strong>dev/js</strong>, and the topmost component is <strong>App.js</strong>. During the componentWillMount lifecycle method, we grab the record ID from the URL, call setState to capture the record ID and use the callback to pass this to <strong>getInitialState</strong>.</p><p><strong>getInitialState</strong> is imported from <strong>DataHandler.js</strong>, which is a module that contains the interactions between the client and Apex controller; note that the same name for the client side and server side functions is convenient, but not required.</p><pre>componentWillMount() {<br> const recordId = getUrlParameters()[“id”];<br> this.setState({<br> RecordId: recordId<br> }, () =&gt; {getInitialState(this)});<br>}</pre><p>Our <strong>getInitialState</strong> method in <strong>DataHandler.js</strong> uses JavaScript remoting to call the <strong>getInitialState </strong>method of the <strong>AccountManagementController</strong> and passes the <strong>RecordId</strong> from state. We use an arrow function as our callback, and break apart the single bundle into different parts of our React state, and we pass the relevant structures down to each of our React components within <strong>App.js</strong>.</p><pre>&lt;div className=”app-container”&gt;<br> &lt;AccountHeader Fields={this.state.Fields} Section={this.state.Sections.get(‘Account_Header’)} Account={this.state.Account} /&gt;<br> &lt;ContactTable Fields={this.state.Fields} Section={this.state.Sections.get(‘Contact_Table’)} Contacts={this.state.Contacts} /&gt;<br> &lt;OppTable Fields={this.state.Fields} Section={this.state.Sections.get(‘Opp_Table’)} Opps={this.state.Opps} /&gt;<br>&lt;/div&gt;</pre><p>Focusing specifically on the <strong>AccountHeader.js</strong> component, we iterate over the array returned from this.props.Fields.get(&#39;Account_Header&#39;) to iteratively create <strong>AccountHeaderField</strong> components.</p><pre>&lt;ul className=”slds-grid slds-page-header__detail-row”&gt;<br> {<br> this.props.Fields.get(‘Account_Header’).map(item =&gt; <br> &lt;AccountHeaderField key={item.name} Field={item} Account={this.props.Account} /&gt;)<br> }<br>&lt;/ul&gt;</pre><h4>Dynamic Section Ordering</h4><p>We had promised the delivery of dynamically ordered sections, and this doesn’t require any JS at all. Using exclusively <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">flexbox</a>, we are able to set the <strong>order</strong> property of each top level <strong>div</strong> rendered by our <strong>AccountHeader</strong>, <strong>ContactTable</strong>, and <strong>OppTable</strong> components.</p><p>Let’s check out this example in <strong>AccountHeader</strong>’s render method:</p><pre>if(this.props.Fields.get(‘Account_Header’) != null) {<br> let flexOrder = {order: this.props.Section.Section_Order__c};<br> <br> return(<br> &lt;div style={flexOrder} className=”slds-page-header”&gt;</pre><p>Before returning our JSX, we create an object that contains styles, which includes our <strong>order</strong> property. We pass this as an inline style in the return, and it thus interacts with the other sections based on <a href="https://flexbox.io/">flexbox’s</a> ordering.</p><p>Our styles in <strong>dev/css/App.css</strong> are super concise; we want to use <a href="http://flexboxfroggy.com/">flexbox</a> with the primary axis being vertical. The inline styles within each component handle the ordering, and we’re done.</p><pre>div.app-container {<br> display: flex;<br> flex-direction: column;<br>}</pre><h4>Ideas for Implementation</h4><p>While this is a trivial example, there’s room to extend this framework further. Here are a few ideas for how you can apply this your development projects and help admins configure their great UIs:</p><ul><li>Bind custom metadata types to specific Record Types for an object</li><li>Define pages that should occur in a multi-step wizard</li><li>Dig further into UI customizations with the <a href="https://www.lightningdesignsystem.com/components/utilities/grid/#flavor-manual-sizing">SLDS Grid’s Manual Sizing</a>, allowing admins to control how to display within each section</li></ul><h4>Test Driving the App</h4><p>Head on over to the <a href="https://github.com/rogeramitchell/dynamically-controlled-vf-react-app">GitHub repo</a> and follow the steps below to try this out in your org:</p><ul><li>Fork the repository and clone to your local machine</li><li>cd to your project folder and run npm install</li><li>After dependencies have loaded, webpack --watch to rebuild your <strong>resource-bundles/AccountManagement.resource/js/app.js</strong> file when components in <strong>dev/*</strong> are changed</li><li>Use <strong>Convert to MavensMate Project</strong> feature to deploy this into your org using MavensMate with Sublime Text / Atom / VS Code</li><li>Deploy your <strong>AccountManagement.resource</strong> bundle to the server and refresh your <strong>AccountManagement</strong> page</li></ul><p>If you’ve done something similar or want to share your thoughts, feel free to leave a comment below, an issue or PR on the <a href="https://github.com/rogeramitchell/dynamically-controlled-vf-react-app">repo</a>, or via Twitter <a href="http://twitter.com/RogerMitchell">@RogerMitchell</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88578bcc4217" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Requestly in Visualforce Development Workflow]]></title>
            <link>https://medium.com/@RogerMitchell/using-requestly-in-visualforce-development-workflow-dd64e5f5998f?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd64e5f5998f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[visualforce]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Thu, 09 Feb 2017 03:30:59 GMT</pubDate>
            <atom:updated>2017-02-09T14:19:30.101Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s time that front-end dev workflow on Salesforce gets an efficiency boost. If you’ve developed any front-end assets on localhost, you may know how incredible it is to use tooling like <a href="http://gulpjs.com/">Gulp</a>, <a href="http://gruntjs.com/">Grunt</a>, and most recently <a href="https://webpack.js.org/">Webpack</a>; updating a function in your JS or changing a style in your CSS causes the page to reload, and you continue forward with development.</p><p>A nearly identical workflow is possible with our Visualforce development workflow by using a static resource bundle, a Chrome extension called <a href="http://requestly.in/">Requestly</a>, and our task runner of choice (in this case, <a href="https://webpack.js.org/configuration/dev-server/">Webpack Dev Server</a>).</p><h4>Prerequisites</h4><p>In order to benefit from developing and serving our front-end components on localhost, we’ll need to have a few things set up first.</p><ol><li>cd to our project’s root folder</li><li>npm init and npm install webpack-dev-server —-save-dev</li><li>Ensure we leverage a static resource the page’s JS/CSS and this is unpacked as a static resource bundle in the IDE</li></ol><h4>Setting Up Webpack Dev Server</h4><p>Now that we have webpack-dev-server installed, we can run a command with Terminal to specify from where we should serve our files. Note that you’ll want to replace the <strong>resource-bundles/RequestlyDemo.resource</strong> with your static resource bundle that appears in your project folder before running the command.</p><p>Run webpack-dev-server --content-base resource-bundles/RequestlyDemo.resource --https in our project folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7qOwUesuh-2q0m95HnKdg.png" /><figcaption>Terminal output that shows webpack-dev-server is running</figcaption></figure><h4>Setting Up Requestly</h4><p>Our files are now served on localhost, so we can use <a href="http://requestly.in/">Requestly</a> to replace requests to Salesforce’s copy of the static resource to our localhost version. Open the Requestly extension by visiting the <a href="http://requestly.in/rules">rules page</a> and click the <strong>+</strong> icon to create a new rule. We’ll use the <strong>Replace Host</strong> configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xz55OZu8r_qwfrogngBt6w.png" /><figcaption>Requestly’s available options for setting up a new rule</figcaption></figure><p>Pop back to our Visualforce page and open Chrome Dev Tools. We’ll inspect the Sources tab to note the URL that Salesforce has for our server side static resource. We should be able to this regular expression to replace a portion of this URL with localhost: /https.*\/resource(\/[0–9]+)?/RequestlyDemo/ig. Note that you’ll need to change <strong>RequestlyDemo</strong> to your static resource’s name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h038jSMLFGlmNcGl9HKIqA.png" /><figcaption>Confirming our static resource appears as a source for our Visualforce page</figcaption></figure><p>Within Requestly, we’ll confirm our regular expression matches the base URL for the static resource with our <strong>Replace</strong> option, and specify our localhost and port as the <strong>With</strong> option. Click <strong>Save</strong> and ensure that the rule is toggled as <strong>Active</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEVDiGnBUTQQwkxTY1QUpQ.png" /><figcaption>Replacing a regular expression for the static resource with our localhost webpack-dev-server</figcaption></figure><h4>Using Within a Development Workflow</h4><p>After saving a change to your local CSS and JS files, refresh the Visualforce page and see the changes implemented. This saves time from deploying the static resource bundle and dealing with any lags with the Tooling and Metadata APIs. Also, creating these changes in localhost can allow other users to test features on the page as you continue development of an additional feature.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F44ILuLTgUlk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D44ILuLTgUlk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F44ILuLTgUlk%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0585f22f2a32660c457d82f5abaab1a/href">https://medium.com/media/c0585f22f2a32660c457d82f5abaab1a/href</a></iframe><p>Note that in the demo above, the page did not initially reflect changes made to main.js and styles.css. By inspecting the sources, it appears the number scheme changed for our server-side static resource. By updating the Requestly rule, we can move forward with our changes.</p><p>I’d love to hear your thoughts about how this can save time in your workflow, and if you have any other tips and tricks to share. Drop a comment below or <a href="http://twitter.com/RogerMitchell">@RogerMitchell</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd64e5f5998f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Driven App Building: A Scalable Way to Testing Your Declarative Apps on Salesforce]]></title>
            <link>https://medium.com/@RogerMitchell/test-driven-app-building-a-scalable-way-to-testing-your-declarative-apps-on-salesforce-acc9456abdac?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/acc9456abdac</guid>
            <category><![CDATA[salesforce-admin]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Sun, 22 Jan 2017 16:54:00 GMT</pubDate>
            <atom:updated>2017-01-22T16:54:00.424Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Test Driven App Building</strong> is similar to writing a test for our Apex code; it proves that our declarative apps are functioning the way that we intended to build them, and alerts us to when a change is causing them to (potentially) function in a way that we didn’t expect.</p><p>We can implement <strong>Test Driven App Building</strong> in two different ways: blue pill, red pill?</p><ul><li><strong>Blue Pill</strong>: write what we’ve deployed, then manually test it every deployment</li><li><strong>Red Pill</strong>: write tests for what we’ve deployed, then run these tests every deployment</li></ul><p>I’m a bit biased, but the first option sounds like a lot of work and has room for error, and the second option sounds like time to get a cup of coffee while Salesforce validates the Rosetta Stone.</p><p>If we choose the <strong>red pill</strong>, it means we roll up our sleeves and write a little Apex, but we benefit heaps of time for every deployment thereafter.</p><h4>Hold on, you want me to write Apex to test every workflow rule?</h4><p>No way! At least, not necessarily. Salesforce allows us to build and deploy changes to our end users in a quick, agile manner, and the end goal is to ensure that our end users have the best experience possible.</p><p>Larger business processes (think: an account onboarding process) benefit from <strong>Test Driven App Building</strong>, as these are critical to our organization’s process and our end users’ ability to do their work. Smaller business processes can also benefit from <strong>Test Driven App Building</strong> when the process has a lot of volume or occurs many times in a given time period, or can cause systems to no longer be in sync (think: integrations).</p><h4>Ok, I’m skeptical… but willing to give this a shot.</h4><p>Great! Let’s consider a use case where we have a custom integration with our finance team’s ERP system, and see how <strong>Test Driven App Building</strong> can help troubleshoot the root cause.</p><p>Universal Containers has an ERP system that manages customer invoices, and a custom integration pushes this data into Salesforce on a nightly basis. We’ve noticed that our numbers are not adding up, as the Finance Team suggests invoices are being paid, but the Sales Team still sees unpaid invoices in Salesforce. What happened? Is the integration not working? Did someone change the integration jobs, or did someone change something in Salesforce?</p><p>Custom integrations may not involve any Apex code, and may rely upon the existing set of APIs provided by Salesforce. We’re a bit in the dark here.</p><p>Let’s rewind the clock and pretend that we had created a test that covers our integration scenario. Our integration creates and updates Invoice records, and we know the set of fields included when the integration was first deployed.</p><p>Alright, let’s fast-forward back to the moment we have an email thread with the Finance and Sales Teams about a discrepancy in invoice numbers. We jump into Salesforce, open up the Dev Console, and run our <strong>InvoiceIntegrationTest</strong>!</p><p>A bunch of seconds pass… (hey, tests aren’t instant y’all!)</p><p><strong>… and we see that our test passes!</strong><br>Great news, we reply to the thread that the integration test shows everything works from the Salesforce side, so the next step in troubleshooting is to check with the team that built out the integration.</p><p><strong>… and we see that our test fails!</strong><br>Yikes! What does the error message say? Is it a <strong><em>field_custom_validation_exception</em></strong>? It seems like there was a change in Salesforce that caused this integration test to fail, so we can advise the Finance and Sales Teams that we think the root cause is in Salesforce, and we’re checking what changed in Salesforce since the integration was deployed.</p><h4>Wow, that’s a lot faster than the hours I’ve spent in the past!</h4><p>Even better (regardless if the test passed or failed)! Since you’re still with me, let’s nerd out a bit and write a sample Apex test for this Invoice scenario.</p><p>Start out by logging into your sandbox (or Developer Edition) org and opening the Developer Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtPse9LDK1I8z_FfoQ42RQ.png" /><figcaption>How to open the Developer Console in Salesforce Classic</figcaption></figure><p>We’ll click <strong>File &gt; New &gt; Apex Class</strong>, and give our test a name like <strong>InvoiceIntegrationTest</strong>.</p><p>Salesforce automatically generates some of the Apex code for us, and we’ll want to modify this slightly. Note that we’re including isTest to identify that this is an Apex test class.</p><pre><a href="http://twitter.com/isTest">@isTest</a><br>public class InvoiceIntegrationTest <br>{</pre><pre>}</pre><p>There are two different scenarios that we wish to test: creating an Invoice, and updating an Invoice. Each of these scenarios will have its own <strong>test method</strong> in our Apex test class.</p><pre><a href="http://twitter.com/isTest">@isTest</a><br>public class InvoiceIntegrationTest<br>{<br> static testMethod void createInvoice()<br> {</pre><pre> }</pre><pre> static testMethod void updateInvoice()<br> {</pre><pre> }<br>}</pre><p>Let’s handle the <strong>createInvoice</strong> part first. We’re going to perform 4 different steps as part of this test:</p><ol><li>Create a new Invoice record: think of this as clicking the “New” button on the Invoice tab</li><li>Set some of the fields on the Invoice record: think of this as filling in fields on a page layout</li><li>Insert the Invoice to Salesforce: think of this as clicking the “Save button” on a page layout</li><li>Check that our fields have the values that we expect: think of this as looking at the Invoice’s detail page and visually checking some of the fields</li></ol><pre>static testMethod void createInvoice()<br>{<br> // Step 1<br> Invoice__c invoice = new Invoice__c();<br> <br> // Step 2<br> invoice.Amount__c = 15000;<br> invoice.Status__c = &#39;Sent&#39;;<br> <br> // Step 3<br> insert invoice;<br> <br> // Step 4<br> invoice = [SELECT Id, Amount__c, Status__c, Date_Paid__c,  Date_Sent__c FROM Invoice__c WHERE Id = :invoice.Id];<br> System.assertEquals(15000, invoice.Amount__c);<br> System.assertEquals(&#39;Sent&#39;, invoice.Status__c);<br>}</pre><p>Our next step is to handle the <strong>updateInvoice</strong> logic. We’re going to piggy back on our <strong>createInvoice</strong> test, but include 2 additional steps since we need to update something about the invoice we create!</p><ol><li>Create a new Invoice record: same as createInvoice step 1</li><li>Set some of the fields on the Invoice record: same as createInvoice step 2</li><li>Insert the Invoice to Salesforce: same as createInvoice step 3</li><li>Change the status field on the Invoice record: think of this as clicking Edit on an Invoice record and changing the Status field</li><li>Updating the Invoice record: think of this as clicking the “Save” button after we edited a field</li><li>Check that our fields have the values that we expect: same as createInvoice step 4</li></ol><pre>static testMethod void updateInvoice()<br>{<br> // Step 1<br> Invoice__c invoice = new Invoice__c();<br> <br> // Step 2<br> invoice.Amount__c = 15000;<br> invoice.Status__c = &#39;Sent&#39;;<br> <br> // Step 3<br> insert invoice;<br> <br> // Step 4<br> invoice.Status__c = &#39;Paid&#39;;<br> <br> // Step 5<br> update invoice;</pre><pre>// Step 6<br> invoice = [SELECT Id, Amount__c, Status__c, Date_Paid__c, Date_Sent__c FROM Invoice__c WHERE Id = :invoice.Id];<br> System.assertEquals(15000, invoice.Amount__c);<br> System.assertEquals(&#39;Paid&#39;, invoice.Status__c);<br>}</pre><p>Awesome! We just built out two tests in our Apex class, and we’re ready to click the <strong>Run Test</strong> button. We’ll see the results appear in the <strong>Tests</strong> tab at the bottom of Developer Console; green checks are good, and red x’s are bad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFLHwtTE1cNotqGJCRGpBA.png" /><figcaption>Running a test and viewing the results in the Developer Console</figcaption></figure><h4>What happens if my test fails?</h4><p>Great question! Let’s create a new validation rule on the Invoice object that will throw an error if our Invoice Status is “Paid” but the Date Paid field is blank.</p><pre>AND( ISPICKVAL( Status__c, “Paid” ), ISBLANK( Date_Paid__c ))</pre><p>Pop back to Developer Console and click <strong>Run Test</strong> again, and we’ll see that one of our tests is now failing in the <strong>Tests</strong> tab. The reason why this test started to fail is because we have a validation rule that prevents <strong>Step 5</strong> from saving the Invoice, since our test is not setting the Date Paid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1Mf_oq_X-Z3tu-sTvrr3Q.png" /><figcaption>Double clicking on a row shows more results to help diagnose the error</figcaption></figure><p>Jumping back to our earlier scenario with Universal Containers, we can see how an innocuous validation rule can potentially cause unexpected results. With our new <strong>InvoiceIntegrationTest</strong>, we’re able to see if our changes to the org’s configuration will impact any critical business processes, even if these business processes don’t involve Apex code!</p><h4>Dang! Test Driven App Building is neat!</h4><p>I’m glad you agree! If you want to install the Invoice object with the validation rule and Apex test that we wrote together, feel free to use either this <a href="https://login.salesforce.com/packaging/installPackage.apexp?p0=04t61000000kf6z">production</a> or <a href="https://test.salesforce.com/packaging/installPackage.apexp?p0=04t61000000kf6z">sandbox</a> link to install into your org.</p><p>I’d also love to hear your thoughts and use cases as you embark on your first <strong>Test Driven App Building</strong> experience! Leave a comment below or throw a mention <a href="http://twitter.com/RogerMitchell">@RogerMitchell</a> on Twitter with any questions, comments, etc!</p><p>NOTE: Medium has some issues displaying code snippets in a meaningful way, so if you’d like a cleaner experience, feel free to check out the <a href="https://github.com/rogeramitchell/BlogPost-TestDrivenAppBuilding">repo on Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acc9456abdac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Comparison Between Process Builder and Apex Triggers]]></title>
            <link>https://medium.com/@RogerMitchell/performance-comparison-between-process-builder-and-apex-triggers-e4a1f455f9c1?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a1f455f9c1</guid>
            <category><![CDATA[salesforce-tools]]></category>
            <category><![CDATA[dreamforce]]></category>
            <category><![CDATA[salesforce-lightning]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Wed, 21 Dec 2016 23:35:13 GMT</pubDate>
            <atom:updated>2016-12-21T23:35:13.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Since introducing Process Builder in 2014, there has been noticeable adoption by admins, app builders, and developers; anecdotally, I have seen it adopted in nearly all of my client orgs. Process Builder provides a declarative mechanism for automating actions that previously were reserved for Apex triggers, and expands the toolset available to non-developer staff.</p><p>However, there seems to be a performance lag when orgs have multiple processes that execute sequentially. I decided to conduct an experiment comparing the performance of Process Builder to Apex triggers. Read on for details about the experiment, and the results!</p><h4>Test Scenario</h4><p>When an Account record is inserted that has a name starting with “Test”, process evaluates to update an Account field, create a new Contact, and a new Opportunity. The new Opportunity causes a second process to evaluate to update an Opportunity field, and create 4 Opportunity Products.</p><p>Our test scenario is a bit contrived, though it illustrates how a process can cause a second process to fire, involving both updates to the record starting the process and inserting records related to that record.</p><p>Below we’re going to compare the performance in two separate cases: creating a new Account record via the Account tab’s New button, and by inserting 100 records using the Apex snippet below. Each test is repeated 10 times using Process Builder to automate the record updates and inserts, and then the processes are deactivated, and Apex triggers are activated that perform the same actions.</p><pre>List&lt;Account&gt; accountList = new List&lt;Account&gt;();<br>for(Integer i = 0; i &lt; 100; i++)<br>{<br>    Account a = new Account();<br>    a.Name = &#39;Test&#39; + i;<br>    accountList.add(a);<br>}</pre><pre>insert accountList;</pre><p>To measure transaction times, Developer Console offers the Execution Overview panel that shows the Timeline of the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHCn1TZL8lxZWlc7Ag18LQ.png" /><figcaption>Developer Console’s Execution Overview panel highlighting the timeline of 100 Accounts being inserted with Process Builder to handle automation.</figcaption></figure><h4>Results with Process Builder</h4><p>When creating a single Account record, the save transaction takes on average less than a second (831 milliseconds). Oddly, all of the transactions have 0 milliseconds spent in “DB” or database, despite records being inserted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Pigyjb3diyxq1Sk2hiiLWg.png" /><figcaption>Inserting an Account and automation via Process Builder</figcaption></figure><p>When creating 100 Account records via an Apex snippet, the save transaction takes on average 17.5 seconds (17546 milliseconds). Each run sees an average of 4 seconds (4264 milliseconds) spent executing Apex, which is most likely due to the anonymous Apex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*5vExXaGVQFJn7dt7uBrpHQ.png" /><figcaption>Inserting 100 Accounts and automation via Process Builder</figcaption></figure><h4>Results with Apex Triggers</h4><p>When creating a single Account record, the save transaction takes on average less than half a second (434 milliseconds).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2_KiRNwxcAOaxEMJrwqG4Q.png" /><figcaption>Inserting an Account and automation via Apex triggers</figcaption></figure><p>When creating 100 Account records via an Apex snippet, the save transaction takes on average 7.5 seconds (7345 milliseconds). Each run sees an average of 5 seconds (4960 milliseconds) spent executing Apex. If we compare this to the prior run with Process Builder, it’s likely that 4 seconds of this relates to the execution of the anonymous Apex block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Wil5eD4wlO3noVgvcqVlCA.png" /><figcaption>Inserting 100 Accounts and automation via Apex triggers</figcaption></figure><h4>Apex &gt; Process Builder (for some cases)</h4><p>Process Builder is a great tool that offers a wide set functionality, though it comes with a cost to performance in more complex cases, with 2x more time spent during the save transaction. When processes cause other processes to fire, it’s worth evaluating whether to move the automation into Apex triggers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a1f455f9c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Invocable Methods to Post into Slack]]></title>
            <link>https://medium.com/@RogerMitchell/using-invocable-methods-to-post-into-slack-743db44866b0?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/743db44866b0</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Wed, 24 Jun 2015 00:43:56 GMT</pubDate>
            <atom:updated>2015-06-24T00:43:56.712Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been on a Slack kick recently, and frankly it’s hard not to be; I’ve seen great success having two organizations leverage it to consolidate team communications and benefit from its automation across development tools and platforms. You may have read <a href="https://medium.com/@RogerMitchell/handling-exceptions-with-salesforce-and-slack-445ec3074b3f">my other post about Slack</a>, which details how to handle exceptions with a combination of Salesforce and Slack.</p><p>Getting away from exception handling, it would be cool to see organization wide alerts flow into Slack. I <a href="https://github.com/rogeramitchell/Invocable-Method-For-Slack">created an Invocable Method</a> that allows system administrators to use Salesforce’s declarative or programmatic development tools to post into Slack. I’ve created an <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm">Invocable Method</a> that allows users to pass attributes required to facilitate a post to Slack via their <a href="https://api.slack.com/web">Web API</a>.</p><ul><li>Token: authentication with the API</li><li>Channel ID: where the post appears</li><li>Post Contents: the body of text that will appear in the post</li><li>Bot Name: the username of the bot that posts in the channel</li><li>Bot Picture: the icon appearing adjacent to the bot</li></ul><p>Invocable Methods are neat, as it allows administrators and developers to use the same framework for achieving a specific goal. For this use case, admins can leverage <a href="https://help.salesforce.com/HTViewHelpDoc?id=process_overview.htm">Process Builder</a> to call Apex and developers can leverage this from within code.</p><h4>Declarative Posts</h4><p>Slack is a tool that many organizations are leveraging to communicate across teams, and it may be worthy to push alerts from Salesforce into Slack. Let’s use an organization called ABC Music Platform that produces a great subscription-based music streaming service. This organization seeks partnerships with record labels, and as part of their partnerships, will need to facilitate new platform features. ABC Music Platform also has users that may need assistance, and occasionally a product team needs to get involved because the issue escalates beyond the customer success team.</p><p>Let’s dive into a deal where ABC Music Platform has a partnership opportunity with Swift Records, a popular country label that has a large fanbase. As part of the partnership, the platform must add additional features for fan/user engagement. This opportunity is flagged as a platform upgrade, and the ABC Music Platform team can receive an update in their <strong><em>#feature-request</em></strong> channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJy7N0EKkS1ZipdnweEtVw.png" /></figure><p>Admins can leverage Process Builder to set up an action on the Opportunity object that will cause a post when certain criteria met. Whenever the “Platform Enhancements” field is changed, a “Post Details to Slack” action is used to call the invocable method via a declarative interface. The list of attributes above were filled out, and we can concatenate various field values to create a meaningful post content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rrAVwGuWYglTTLg26bmiQ.png" /></figure><p>If you need help understanding how to retrieve your Channel ID and Token, check out <a href="https://medium.com/@RogerMitchell/handling-exceptions-with-salesforce-and-slack-445ec3074b3f">my previous post</a> and scroll down to the section called “How do I set up Slack with Exception Force?”… this has the details about creating an authentication token and a channel ID.</p><h4>For Coders</h4><p>Leveraging the Invocable Method is pretty simple, we create an instance of the Message class (from within the PostSlackMessage class), and set the variables in a similar fashion as we saw in the screenshot above… except we use code!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*85GVp1SFuwuwd-7-MZbEYA.png" /></figure><p>We manage our licenses through Salesforce, allowing our customer success team to resolve individual and corporate subscriptions from within the Service Cloud Console, and nightly we ensure that trials are deregistered. Our goal is to see these appear in the <strong><em>#job-manager</em></strong> channel. To achieve a post like this, we can add the following code in our batch classes to alert us when everything goes smoothly.</p><pre>List&lt;PostSlackMessage.Message&gt; messageList = new List&lt;PostSlackMessage.Message&gt;();<br>PostSlackMessage.Message successMessage = new PostSlackMessage.Message();<br> <br>successMessage.channelId = ‘C09876543’;<br>successMessage.iconUrl = ‘<a href="http://placehold.it/48x48&#39;">http://placehold.it/48x48&#39;</a>;<br>successMessage.text = ‘License management finished processing necessary updates… all trial users have been booted :)’;<br>successMessage.token = ‘x1234–1234567890-asdf’;<br>successMessage.username = ‘LicenseManager’;</pre><pre>messageList.add(successMessage);</pre><pre>PostSlackMessage.PostSlackMessage(messageList);</pre><h4>How do I use this?</h4><p>You can either deploy the classes from <a href="https://github.com/rogeramitchell/Invocable-Method-For-Slack">this Github repo</a>, or install to your <a href="https://login.salesforce.com/packaging/installPackage.apexp?p0=04t1a000000R7Jd">production</a> / <a href="https://test.salesforce.com/packaging/installPackage.apexp?p0=04t1a000000R7Jd">sandbox</a> orgs via the linked packages. Process Builder and executing anonymous blocks from Dev Console are two great ways to try out the utility and see if you are interested in leveraging within your organization.</p><p>If more than 50 records are included in any given call to this method, only the first 50 will have posts sent to Slack (provided no other future callouts are within the transaction). This is a limitation that teams will need to be aware of when using this Invocable Method, as it is at the mercy of the Salesforce governor limits.</p><h4>What if I have questions or feedback?</h4><p>I would love to hear it! Please reach out as comments on this article, via Twitter <a href="https://www.twitter.com/RogerMitchell">@RogerMitchell</a>, or as issues on the <a href="https://github.com/rogeramitchell/ExceptionForce">Github repo</a>. I hope you enjoy using this to centralize your team’s notifications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743db44866b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Exceptions with Salesforce and Slack]]></title>
            <link>https://medium.com/@RogerMitchell/handling-exceptions-with-salesforce-and-slack-445ec3074b3f?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/445ec3074b3f</guid>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Thu, 11 Jun 2015 21:18:12 GMT</pubDate>
            <atom:updated>2015-06-11T21:18:12.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Exception handling is a great practice for any developer, though Salesforce developers only get exceptions if they are monitoring a debug log, or were the last user to deploy components to production. This paradigm is fine for smaller orgs, but it cannot scale to support ISVs or teams that support multiple orgs.</p><p>I decided to create <a href="https://github.com/rogeramitchell/ExceptionForce">ExceptionForce</a> after mulling over how to collect exceptions that occur on platform, and had inspiration from a <a href="https://developer.salesforce.com/page/An_Introduction_to_Exception_Handling">Salesforce Developers blog post</a> back in October 2014. The architecture is fairly simple, whenever you leverage try…catch, you call a method in a utility class that will “handle” the exception. Handling an exception has a few flavors depending upon how you’d like to receive notifications about exceptions.</p><pre>try {<br>  insert accountList; <br>} catch(Exception e) {<br>  ExceptionUtils.handleException(e, true, true);<br>}</pre><p>Passing the exception caught along with two boolean parameters controls how the method will proceed. Our first boolean sets whether to create a record in the Exception custom object, and our second boolean sets whether to send a post to the <a href="https://api.slack.com/web">Slack Web API</a> (specifically the <a href="https://api.slack.com/methods/chat.postMessage">chat.postMessage</a> method).</p><p>Both flavors allow you to capture the following details about the exception, and with the Exception custom object, you can leverage declarative options to send email alerts or post to a Chatter feed.</p><ul><li>Cause</li><li>Line Number</li><li>Message</li><li>Stack Trace String</li><li>Type Name</li></ul><h4>Why use ExceptionForce?</h4><p>Capturing exceptions based on your existing codebase is as simple as adding a line to every <strong><em>catch{}</em></strong>, and this will allow your team to centralize issues and manage them accordingly. I decided to keep this open source and as an unmanaged package (for an easier installation) to allow teams to extend it further, or embed it further into their workflows.</p><h4>How do I install and set up ExceptionForce?</h4><p>You can either <a href="https://github.com/rogeramitchell/ExceptionForce">clone this Github repo</a> and deploy the components into your org, or use the installation links for your <a href="https://login.salesforce.com/packaging/installPackage.apexp?p0=04t1a000000QuBv">production</a> or <a href="https://test.salesforce.com/packaging/installPackage.apexp?p0=04t1a000000QuBv">sandbox</a> orgs. If you are interested in Slack integration, skip a section below that details specifically how to set up a Slack integration with ExceptionForce.</p><p>Here’s a code snippet that you can execute in your Developer Console’s Execute Anonymous window. This particular case will fail because we are attempting to create an Account without specifying a value for the Name field.</p><pre>// Generate an exception, catch, and log with ExceptionForce<br>Account fail = new Account();</pre><pre>try{<br> insert fail;<br>} catch(Exception e) {<br> ExceptionUtils.handleException(e, true, false);<br> <br> System.debug(‘### getCause ‘ + e.getCause());<br> System.debug(‘### getLineNumber ‘ + e.getLineNumber());<br> System.debug(‘### getMessage ‘ + e.getMessage());<br> System.debug(‘### getStackTraceString ‘ + e.getStackTraceString());<br> System.debug(‘### getTypeName ‘ + e.getTypeName());<br>}</pre><p>We have set our <strong><em>handleException()</em></strong> method to create a record in the Exception object and not post the details to a Slack channel. Below is an example of what this exception record looks like within ExceptionForce.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DrEtuZ98Ej0EYfudLrTFw.png" /><figcaption>Exception caught and created as part of our anonymous block above.</figcaption></figure><h4>How do I set up Slack with ExceptionForce?</h4><p>If you’re interested in Slack, it’s assumed that you already have an account; if not, go check it out at <a href="https://slack.com/">Slack.com</a>. You’ll need to create an authentication token, which can be done from <a href="https://api.slack.com/web">this site</a>. Copy and paste the string that’s blocked out by the big orange bar below; you’ll use this when creating a Custom Setting a few steps later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvfykN1gFZQwFQuixagzvQ.png" /></figure><p>Next, we’ll want to retrieve the channel ID that will be used for our integration. You may want to create a new channel first if you don’t have a centralized #errors channel, or wish to keep Salesforce exceptions to its own channel. Retrieving a channel ID can be accomplished by using the <a href="https://api.slack.com/methods/channels.list/test">channel.list</a> method directly from the browser. Check the JSON returned for the name of your channel, and grab the ID (below this is C12345678).</p><pre>{<br>    &quot;ok&quot;: true,<br>    &quot;channels&quot;: [<br>        {<br>            &quot;id&quot;: &quot;C12345678&quot;,<br>            &quot;name&quot;: &quot;errors&quot;,<br>            &quot;is_channel&quot;: true,<br>            &quot;created&quot;: 10101010,<br>            &quot;creator&quot;: &quot;U0000000&quot;,<br>            &quot;is_archived&quot;: false,<br>            &quot;is_general&quot;: false,<br>            &quot;is_member&quot;: true,<br>            &quot;members&quot;: [<br>                &quot;U0000000&quot;<br>            ],</pre><p>Our final step is to create a record of the Slack Service custom setting. We’ll use the token and channel ID, along with a few other attributes to personalize our bot with a name and icon.</p><ul><li>Name: doesn’t really matter… call it “Slack Errors”</li><li>Token: copy/paste the token from our first step</li><li>Channel ID: copy/paste the channel ID from our second step</li><li>Username: the name of the “bot” that posts into the channel</li><li>Icon URL: the avatar of the “bot”</li><li>API URL: <a href="https://slack.com/api/chat.postMessage">https://slack.com/api/chat.postMessage</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*q-oFs-xacJM7cazEE5c5Kw.png" /></figure><p>After you finish this, you can go back to the Developer Console and execute the script we used above, but set the third parameter of <strong><em>handleException() </em></strong>to true.</p><pre>// Generate an exception, catch, and log with ExceptionForce<br>Account fail = new Account();</pre><pre>try{<br> insert fail;<br>} catch(Exception e) {<br> ExceptionUtils.handleException(e, true, true);<br>}</pre><p>You should see a post appear in your Slack channel that details the exception. Below are a few from QA testing the package earlier today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOiJ4311QMUo48vRKXfdnQ.png" /></figure><h4>What are the next steps?</h4><p>I would love to collect feedback on ExceptionForce, either as comments on this article, via Twitter <a href="https://www.twitter.com/RogerMitchell">@RogerMitchell</a>, or as issues on the <a href="https://github.com/rogeramitchell/ExceptionForce">Github repo</a>. I hope you enjoy playing or working with it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=445ec3074b3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple + Square + Venmo = Banking Trifecta]]></title>
            <link>https://medium.com/@RogerMitchell/simple-square-venmo-banking-trifecta-d2e85df3d61e?source=rss-56f6ed5904f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2e85df3d61e</guid>
            <dc:creator><![CDATA[Roger Mitchell]]></dc:creator>
            <pubDate>Thu, 31 Jul 2014 17:29:49 GMT</pubDate>
            <atom:updated>2014-07-31T17:53:03.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*UsDTK9NUJrnFyp3F-p2quQ.png" /></figure><p>10 years ago, we didn’t have banks that only existed virtually, accessible by phone, web, and mobile apps. Banks were still brick-and-mortal locations with a network of ATMs, and a series of fees were charged for out-of-network ATM transactions. Depositing funds in cash and checks were the same process, an errand to some place open on weekdays (or Saturday mornings… so progressive), amounting to hours of a customer’s time every year.</p><p>18 months ago, banks like <a href="http://www.schwab.com/public/schwab/banking_lending">Charles Schwab</a> and <a href="https://www.simple.com/online-checking-account">Simple</a> had already launched online-only banks that provided users with a way to still manage their money, get cash from <a href="https://www.simple.com/faq#does-simple-charge-fees">ATMs without paying fees</a>, and make check deposits from their mobile device… without the hassle of visiting a branch. A problem still exists, where cash transactions leave customers with pocket change or a delay to access funds electronically by sending cash to central processing facility (the only branch).</p><p>Abstracting beyond this, we live in a world where small businesses are leveraging point-of-sale systems like <a href="https://www.squareup.com/">Square</a> to easily charge customer credit cards or accept electronic payments, and peer-to-peer payment solutions like <a href="https://www.venmo.com/">Venmo</a> to send funds to one another.</p><p>PayPal tried to tackle both of these markets, with their <a href="https://www.paypal.com/webapps/mpp/credit-card-reader">PayPal Here</a> mobile card reader, and their existing network of businesses and consumers using PayPal to send funds. However, from a consumer’s perspective, there’s a key failure point: funds still take days to process. Venmo cut this process to <a href="https://help.venmo.com/customer/portal/articles/1322614-how-long-do-cashouts-take-">next business day</a> for their users so long as requests are made before 7pm ET.</p><p><strong>How can we transform this for the customer? </strong>Provide a single platform for banking and transacting between businesses and peers.</p><p><strong>How do we accomplish this experience?</strong> Merge an online bank, a business point-of-sale company, and a peer-to-peer payment service. Extend business checking accounts to customers from Square, and personal checking acounts to customers from Venmo.</p><p><strong>Why do we transform this space?</strong> Customers have a single place to manage their finances, and for small businesses, a box of e-receipts. Businesses have a social platform to reach out to customers, and can provide swipeless payment. Future enhancements can be made through rewards programs based on transactions or proximity (thinking iBeacons here).</p><p><strong>Bonus:</strong> Rollout something similar to, or offer a connection with, Mint.com to enable users to manage their finances alongside e-receipts for business and personal banking customers.</p><p>What do you think about this? Do you use Venmo, Square, Simple? How could this enhance the way you transact and bank?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2e85df3d61e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>