Showing posts with label FuseIT. Show all posts
Showing posts with label FuseIT. Show all posts

Monday, March 22, 2021

FuseIT SFDC Explorer 3.16.21081.2 - Spring '21

Another roundup of some of the changes to the FuseIT SFDC Explorer since the 3.15.20209.3 release.

Apex class and trigger version highlighting

Ideally all apex classes and triggers within an org would be kept within the last 3 years releases (the last 9 API versions). The API version column will be coloured to indicate how far behind a particular class or trigger is.

Export metadata packages from package builder

Added buttons to "Deploy Selected Files" package builder to export the selected metadata as a package. Either a complete zip or just the package.xml

Other changes 3.16

  • SFDCExplorer: Surface exceptions when listing Salesforce reports via a dialog.
  • The sObject metadata DataCache no longer internally stores unique mappings for field describes, relationships, or childrelationships. These are still accessible via existing methods.
  • Complete update to Spring `21 (v51.0). Update the Bulk API XSD.
  • SFDCExplorer: Detect if there are metadata API version changes when building up a package to deploy
  • SFDCExplorer: double click to login as an SFDX CLI org.
  • SFDCExplorer: Context menu option to format a SOQL query in a debug log row.
  • SFDCExplorer: Improve Executed Units support for workflow and flow events.
  • Improve support for deploying Profile metadata
  • Salesforce MetadataServiceWrapper - Expose CreatePackageXmlAsString to create the package.xml for a collection of metadata paths and return it as a string.
  • SFDCExplorer: Expose the debug log request identifier in the logs view.
  • SFDCExplorer: Highlight Flow errors in the Apex log timeline
  • SFDCExplorer: Authenticate from serverId and URL in query string
  • Split out OAuth (RefreshToken) and JWT LoginDetails to dedicated objects. Added new SfdxLoginDetails for connection strings against the SFDX CLI.
  • Improve formatting of SalesforceResultException FailedSaveResults.
  • Support for metadata deployment of static resources
  • SalesforceIdKeyPrefix - Raise warnings if there is a keyprefix conflict for the current Salesforce user.
  • WSDL2Apex: Expand ability to search for missing XML Namespaces
  • Support for deploying Profile Metadata
  • SFDC Explorer: Improve error handling when there is a timeout retrieving the sObject metadata to populate the entity tree. Retry with a reduced batch size from the detault 100 sObjects.
  • Weekly Data Export tooling - handle premature response stream termination. Improve logging status messages related to downloading data exports.
  • SFDCExplorer: Deploy Profile Metadata
  • SFDCExplorer: handle exceptions with checking test status via polling

Monday, July 27, 2020

FuseIT SFDC Explorer 3.15.20209.3 - Summer '20

Another roundup of some of the changes to the FuseIT SFDC Explorer since the 3.13.20008.1 release.

Display the primary sObject type for a SOQL query in the executed units

When looking at the "Show Executed Units" for a debug log that includes SOQL queries there is a new "SOQL Primary sObject" column. This makes it easier to sort the SOQL queries in the transaction by the sObject they were operating over.

There is also a new context menu option in the executed units area to filter the main log view to just the selected events.

Other changes include tracking Flow executed units and SOQL Total Rows metrics from debug logs.

Add the MetadataComponentDependency API calls via the Bulk API 2.0

Previously the Metadata Dependencies tab was limited by the underlying MetadataComponentDependency API only supporting queries over 2,000 records in a single query. Switching to the bulk API expands this out to 100,000 dependency records.

There is also a new experimental graph format called "Microsoft Automatic Graph". This will use a built in graph layout tool. It is no where near as powerful as Gephi, but it is built in and allows you to gradually build the graph up. E.g. try starting with a single ID against "Where is it used" and then using the context menus to expand the graph incrementally.

Rebuilt login and authentication controls.

The various login and authentication controls that are displayed on app startup have a more consistent UI. For example, they have a consistent Login button.

Other changes 3.15

  • Update SalesforceSession so that all APIs are working against v49.0 - Summer 20
  • Apex logging - add SOQL_EXECUTE_EXPLAIN Log event
  • Update SOQLResult column names when the defaultNamespace is defined. Includes first level relationship fields.
  • SFDCExplorer: Executed Units Context Menu to set Apex Log filter
  • SFDCExplorer: Show a message if there are issues showing an individual entity
  • SFDCExplorer: Support for flow log message types. Guard against debug logs with recursive search depth that is too great.
  • SFDCExplorer: Exception Handling when showing reports.
  • wsdl2apex: Warn if the schemaTypeName is missing.
  • SFDCExplorer: Expand Graph search ability
  • SFDCExplorer: Format VF_ log events in the timeline Handle deeply nested log structures to prevent stack overflows.
  • SFDCExplorer: Format byte size of log. Handling clicking a record ID in the log that doesn't exist in the current org. Option to format Callout requests in the debug log.
  • SFDCExplorer: Ensure the popup window that shows SOQL sub query results has a unique name so that the caching key is unique.
  • Tooling API. Check access to the DebugLevel metadata before attempting to query it.
  • SFDCExplorer: always prompt for directory to save metadata to.
  • Update All API versions to Spring 2020 (v48.0)
  • SFDCExplorer: Update .NET Framework version to 4.7.2 and add support for scaling to high DPI monitors.
  • SFDCExplorer: Update to cs31623 to allow for variation in the instanceUrl provided by the SFDX CLI
  • SFDCExplorer: Auto expand the test class search node when searching. Detect test classes in the queued state
  • SFDCExplorer: Export the results of a Bulk CSV load. This is useful if there where errors with the operation on individual records.
  • SFDCExplorer: Log metrics for callouts
  • Tooling API: Correct updating the log levels on TraceFlags

Thursday, February 13, 2020

FuseIT SFDC Explorer 3.13.20008.1 - Winter '20

Another roundup of some of the changes to the FuseIT SFDC Explorer since the 3.12.19175.1 release.

Redesigned Apex Tests selector

The Apex test selection control has been reworked to include a top level node for the last known state of each test method. This allows you to monitor the accumulated test results from a single location. If you redeploy one of the test cases in question it will reset to an unknown status.

Updates to the Debug Log Executed Units

In the last release I put in the first version of the Executed Units control. This release builds on that.

It is now possible to mix and match the different log types. So you can focus on, for example, just the SOQL queries.

The same toolstrip includes a button to export the executed units data.

Smaller generated Wsdl2Apex classes

If you've ever looked closely at the Apex classes that Wsdl2Apex generates you'll notice a recurring string - the namespace of the the root element. Depending on the WSDL it's not uncommon for this same string to be repeated thousands of times in the generated Apex class. This update will now generate a single static final to handle the repeated usages.

New controls for exploring Execution overlays, including heap dumps

The developer console currently provides a viewer for execution overlay output created by a ApexExecutionOverlayAction record. This includes the Heap Dump, which has all sorts of interesting details about the data stored in heap/memory for the transaction at the the point of time the overlay was captured.

Right now it mostly just replicates the existing developer console functionality and allows browsing the stored objects by type.

Other changes 3.13

  • [cs32197] SFDCExplorer: Option to save a debug log directly to disk.
  • [cs32152] SFDCExplorer: Auto add metadata files when adding package components. Update display of Metadata Deploy results.
  • [cs32150] SFDCExplorer: Allow the target save directory to be specified when doing an unpackaged metadata export (if the working directory isn't accessible)
  • [cs32149] SFDCExplorer: Use internal list of known key prefixes with the Entity Explorer
  • [cs32148] SFDCExplorer: Option on running SOQL queries to include deleted rows
  • [cs32003] Update to Winter '20 release. v47.0
  • [cs31838] Wsdl2Apex: Handle an operation binding with no output. Raising a warning for a missing portType rather than an exception.
  • [cs31820] SFDCExplorer: Hide JavaScript errors during OAuth login

Monday, June 24, 2019

FuseIT SFDC Explorer 3.12.19175.1 - Summer '19

Another roundup of some of the changes to the FuseIT SFDC Explorer since the 3.11.19071.3 release.

Fix for Salesforce breaking the Partner API

One of the primary reasons to use the Partner API in an application is that it is org agnostic. It doesn't really care which org you are connecting to and will adjust to fit the shape of the org it is currently working with. So as long as you don't change the API version in the URL it will keep working indefinitely. Or at least, that is the theory...

Sadly, recent changes around the Real-Time Event Monitoring Beta caused metadata on a JSON field type to leak back into older Salesforce API versions. See Known Issue: DescribeSObject call using the v45.0 Partner API are failing due to a complex type(json) that isn't defined in the WSDL.

By updating to v46.0 of the Partner API we now avoid this issue. In older version it will manifest as a "There is an error in XML document" exception when making the describe call.

View Executed Units from an Apex Log

It's true, the Developer Console already has this information in a sub tab under the Execution Overview. Right now my version just shows the execution count for each Apex method and the basic execution time stats. It if isn't showing up, try turning on the timeline or parse tree first. The debug log will need to show the METHOD_ENTRY and METHOD_EXIT entries, so it the Apex Code logging level will need to be FINE or lower.

Wsdl2Apex : Make it easier to debug out stub objects

Currently, if you try and debug out any of the proxy sObjects that get created for a SOAP callout you end up with a ton of extra *_type_info arrays. While necessary for WebServiceCallout.invoke they have zero usage in debugging the state of the request. They are generally constant and don't really reflect the useful state details.

I'd previously written about using JSON serialization to make repeating a SOAP callout easier. Then it occured to me, why not make all the _type_info arrays transient. Then they won't even appear in the debug output. That's exactly what I've done with the current WSDL2Apex build.

Sadly, transient doesn't work for object.toString(). I did raise an idea for it - Provide a mechanism to exclude object variables/properties from toString()

Reciprocal Logging Event selection and highlighting

There are additional context menu options on a debug log to navigate between related opening and closing events. When applicable you can also select the parent event.

Other changes 3.11

  • Update all API calls to use v46.0 Summer '19
  • Support for monitoring multiple test jobs.
  • ApexTestRunner: New async methods for checking test status. Beta throttled test runner.
  • Fix bug where the 10th column in SOQL results was always being blanked out.
  • Data Export CLI: Allow for parameters to vary in order.
  • Expanded support for deploying different Metadata types.
  • MetadataServiceWrapper - Support for .layout metadata types. Improve creation of package zips - only create the required folders.
  • Option to extract login credentials from a URL formed with "un" and "pw" query string parameters.
  • Wsdl2Apex: Handle SimpleType parameters. Warn if a Union simpleType is encountered.
  • Fix serverURL construction from sfdx cli logins.
  • Handle exceptions with SFDX logins

Tuesday, March 12, 2019

FuseIT SFDC Explorer 3.11.19071.3 - Spring '19

Another roundup of some of the changes to the FuseIT SFDC Explorer since the 3.9.18190.1 release.

Bypass sObject types based of suffix to speed up metadata retrieval

With the update to v45.0 of the APIs there is now describe metadata coming back for change data capture with the suffix __ChangeEvent. This can be useful, except every custom object also gets a change event. If you have a large number of custom objects it can quickly become overwhelming.

I've added a filter option to the sObject metadata browser that defaults to only showing __c, __mdt, and __e. Other options can be turned on if you want to see them. A refresh is required for the changes to take affect.

Expanded Asynchronous Test Results view

After the async tests have finished running you will set the total duration by Apex class and method. This can be useful for identifying which test methods contribute the most to the overall test run time.

Expose the logging levels in the menu

You can alter the current logging levels for the current DebugLevel and then use "Update Current TraceFlag" to apply them to Salesforce.

The "Disable Logging" menu option will remove the current TraceFlag, which will stop further logging from occurring.

Wsdl2Apex

There have been a number of changes to the Wsdl2Apex processing to support more edge cases:

  1. Allow for schema imports via schema imports (nested imports). Includes checks for circular references.
  2. If the complex type can't be found in the current schema search the imported schema for it.
  3. If a SimpleType has a restriction that isn't primitive then search the underlying types for the primitive type that can be converted to Apex.
  4. Detect repeated imported schema target namespaces
  5. Use common code to create Apex class names from complex types.
  6. Add generated Apex comments to classes that extend a base type.
  7. Attempt to compile the XmlSchema to resolve groups so they can be automatically expanded.
  8. Include warning messages on web methods where the return type can't be resolved from the namespace.

Include Apex class name in code coverage breakdown

The Apex class name and test method name will be included with the class coverage breakdown details.

JWT Authentication for Salesforce sessions

It is now possible to use the OAuth 2.0 JWT Bearer Token flow to authenticate with Salesforce. I'll expand on the steps to do this shortly, which will include configuring the connected app and registering the X509 Certificate.

Other changes 3.11

  • Middle click to hide tab. Improve tab hiding.
  • Improve support for using the ToolingAPI in the EntityViewer.
  • If directly updating a nullable int in the SOQL results treat it as such (rather than a string)
  • Format a VF_PAGE_MESSAGE in the log timeline
  • Format display of ApexResult and HeapDump from the Tooling API SOQL Queries.
  • Allow for a CultureInfo.DateTimeFormat.TimeSeparator other than ":". Force the SOQL building code to use the InvarientCulture so the required format is applied.
  • Update core SalesforceSession to use v45.0 (Spring 19) APIs
  • For the Apex Log Stack, include the Soql Execute Count
  • Option to run the most recent async test cases again after a successful metadata deployment.
  • EntityViewer - Allow for ToolingAPI entities.
  • Event Log Viewer. Only show the first 4000 rows of data.
  • Log Timeline control. Show icons for Test.startTest() and Test.stopTest() if they are detected.
  • Handle failure to query for recent apex test runs.
  • When generating anonymous Apex to get the current Session ID include the SalesforceBaseUrl
  • Code Generation - If generating without custom fields, exclude picklist values containing "__". These typically represent relationships to custom sObjects
    Detect and skip duplicate picklist value entries.
    Fix the generated properties for *Picklist to set based on the enum value rather than the description attribute.
    Detect references to sObjects that aren't exposed via the metadata.
  • Regenerate sObjects (plus associated services and data sources) for API v44.0.
  • CodeGeneration - If configured, exclude relationships to custom fields.
  • Don't generate types for __ChangeEvent, __History, __Share
  • CodeGeneration - generate "extends" for Apex classes extending other classes.
  • Expand details for WebServiceCallout.invoke with comments.
  • ApexClass (for generation) - Track if the Apex classes extends a base class.
  • FieldService - When extracting child elements from a query result skip nodes that aren't XmlElements.
  • ToolingServiceWrapper - Add describeGlobalCached() that caches describeGlobal() to improve performance.
  • SalesforceSession - If an exception occurs with a WebRequest include the complete URL in the Exception.Data
  • Internal caching of the Tooling API DescribeGlobalResult Metadata
  • Auto-size columns in SOSL & single page SOQL results
  • Improve usage of direct Csv loading. Support bulk load for larger operations. Allow the primary sObject type to be defined.
  • Change the Apex log layout with the treeview between horizontal and vertical.
  • Define logging levels via common menu, Handle hitting the maximum debug log count
  • Capture SSL/TLS config issues and provide help link to dedicated help page.
  • When checking metadata deployment successes, highlight changed components vs. unchanged.

Monday, July 23, 2018

FuseIT SFDC Explorer 3.9.18190.1 - Summer '18

Another roundup of some of the changes to the FuseIT SFDC Explorer since the 3.7.17230.1 release.

Display additional columns for the Apex Log timeline (Experimental)

Let's say you just ran all the tests in your org in parallel and captured the debug logs for each transaction. Now you have a huge number of debug logs to peruse, but where to start?

Experimental features that I've only tried a few times to the rescue!

By double clicking in the Timeline column cells the full debug log will be pulled down and converted to a timeline. I'm still experimenting with this. Certainly having all the timelines shown at different scales is a bit problematic. It's hard to get a sense of how long the actual transaction took relative to the adjacent ones.

I might instead take a different approach here and extract some metadata from the debug log and just show the core details. I'd look for things like hitting limits, throwing exceptions, slow DML, etc...

Button to delete ALL ApexLog's in an org.

It's a small thing, but currently with Summer '18 it is all to easy to run into a message like:

The Developer Console didn't set the DEVELOPER_LOG trace flag on your user. Having an active trace flag triggers debug logging. You have 318 MB of the maximum 250 MB of debug logs. Before you can edit trace flags, delete some debug logs.

Then you get to play a game of whack-a-moleApexLog with the Tooling API to clear them all out and then get on with your day. This button on the Apex Logs tab reduces it to a single click.

You might also like to vote for the idea: Allow TraceFlags to indicate that Debug logs can be deleted automatically. Adding a TTL and automatic purge of older logs would avoid most of these issues while still being flexible if you needed longer term logging.

Show total counts per log category

The percentage that each log category contributes to the overall log size has been added to the footer. This can be useful for adjusting the log levels when the logs are getting too noisy or large.

Skip Code Coverage

With Summer '18 it is possible to opt out of collecting code coverage with a test run. This can save some time when running the test cases if you don't require the coverage data.

Additional metadata deployment details

When selecting individual metadata files to deploy details such as path, local file system data modified, and CRC are displayed.

Other changes 3.9

  • ApexLogContentControl - Format "SkippedBytesOfDetailedLog". Shortcut to line. Protected against parsing multiple log models at the same time.
  • Expose the Duration in the ApexLogTreeViewUserControl. Color code the Event column
  • ApexLogEntry - Prevent recursion in the model. New properties for Text, Message. Dedicated LimitUsageForNsApexLogEntry ApexLogEntry
  • Option to display timeline bookmarks over thumbs. Detect and highlight LimitUsage warnings and highlight in timeline. Display log running events (> 500ms) as lines in the timeline.
  • Make CSV field name checking case insensitive.
  • When searching for a term in a debug log, ensure that line scrolls into view.
  • When listing Apex classes include an "Uncovered Lines" column
  • Emphasize the Warning and Error entries with larger bars
  • ApexLogModel: Handle CODE_UNIT_STARTED for Validation. Reparent when transitioning from CUMULATIVE_LIMIT_USAGE_END to CODE_UNIT_STARTED without intermediate CODE_UNIT_FINISHED
  • PackageCreation - Include additional metadata when performing a HashDiff on a folder.
  • WSDL2Apex: Skip Complex Content Restrictions (with a warning) rather than throw an exception.
  • WSDL2Apex: Reset stored web service metadata between runs.
  • ApexLogService - Expand LogMessage enum with missing records
  • Update SalesforceSession to use Summer '18 v43.0 API version
  • T4 Code Generator - Allow for sObjects with no record types defined
  • SalesforceSession - Support for visualforce.com as a SOAP Partner URL
  • SalesforceServiceWrapper - Improve performance of ObjectTypeFromId(string id) for looking up the sObject type based on the keyprefix. EntityServiceGenerator.tt - Don't include a custom objects keyPrefix in RegisterKeyPrefixObjectType by default.
  • Include dedicated columns when listing Apex classes for Lines covered and Total lines
  • ApexClassService - Handling missing SOSL search results when looking for test classes.
  • MetadataServiceWrapper - include support for deployment of permissionsets
  • SalesforceException - Log direct web request with cookie exceptions.
  • Wsdl2Apex - handle services that require specific casing on the service URL query string
  • ToolingServiceWrapper - Check for API access to sObjects ApexOrgWideCoverage and ApexCodeCoverageAggregate before querying.

Other changes 3.8

  • Data Export Console: Support for connection strings using RefreshTokens rather than usernames and passwords.
  • Options to metadata deploy Aura components
  • Apex Test Results - Expand nodes to show test case failures initially.
  • UI - Improve menu overflow options
  • UI - Track selected log event as the DataGrid scrolls
  • Data Export Console - Improvements to parameter validation. Especially cases where the wrong number of parameters are provided.
  • Option to collapse/expand the log selection with the log viewer.
  • MetadataServiceWrapper: deploy aura components in packages.

Other changes 3.7.17251.2

  • FitDx: --filter option for user defined events. --summary option for count by event type.
  • Add optional allowExistingSObjectsWithoutId="true" to the binding configuration element to allow sObjects to be created with a null Id. Typically this isn't allowed as the ID is used to control insert/update operations and to identify relationship types. This setting can be used for more basic SOQL queries where the results won't be subsequently used for DML.

Friday, September 22, 2017

Teaching an Old Log Parser New Tricks - FIT sfdx CLI plugin

I've currently got two problems with the prototype FitDX Apex debug log parser I released a couple of weeks ago.

  1. It comes from the FuseIT SFDC Explorer source and is excessively large for what it does. It's got a lot of baggage for features it doesn't currently expose.
  2. To be a native SFDX CLI plugin I need to be working from node.js.

Enter Edge.js and it's quote from "What problems does Edge.js solve?"

Ah, whatever problem you have. If you have this problem, this solves it.

--Scott Hanselman (@shanselman)

As promised, it does what it says on the box and helps solve both problems by connecting the .NET world with node.js - in process.

In my case I've got a .NET library that has many years of work put into it to parse Apex debug logs from a raw string. It's also still actively developed and utilized in the FuseIT SFDC Explorer UI. Between that and my lack of experience with node.js I wasn't in a hurry to rewrite it all so it could be used as a native SFDX CLI plugin. While I still needed to reduce the .NET DLL down to just the required code for log parsing I don't need to rewrite it all in JavaScript. Bonus!

This seems like a good place for a quick acknowledgement to @Amorelandra for pointing me in the right direction with node.js. Thanks again!

With the edge module the node.js code becomes the plumbing to pass off input from the heroku plugins to my happy place (the .NET code). And it is all transparent to the user (assuming the OS specific edge.js requirements are meet). A big bonus being a plugin is that it gives me a prebuilt framework for gathering all the inputs in a consistent way.

I used Wade Wegner's SFDX plugin as a boiler plate for integrating with the cli, chopped most of it out, and kept the command to pull the latest debug log from an org. This debug log is then feed directly into the .NET library to use the existing FuseIT parser.

Enough patting myself of the back for getting this all working. How does it work in practice?

Summary

Like with fitdx, this will give you a count for each event type that appears in the log.

>sfdx fit:apex:log:latest -u <targetusername> --summary
41.0 : 41.0 APEX_CODE,DEBUG;APEX_PROFILING,NONE;CALLOUT,NONE;DB,INFO;SYSTEM,INFO;VALIDATION,INFO;VISUALFORCE,NONE;WAVE,INFO;WORKFLOW,INFO
INFO;WORKFLOW,INFO
CODE_UNIT_FINISHED : 2
CODE_UNIT_STARTED : 11
CUMULATIVE_LIMIT_USAGE : 18
CUMULATIVE_LIMIT_USAGE_END : 18
DML_BEGIN : 22
DML_END : 22
ENTERING_MANAGED_PKG : 768
LIMIT_USAGE_FOR_NS : 54
SOQL_EXECUTE_BEGIN : 25
SOQL_EXECUTE_END : 25
USER_DEBUG : 2
USER_INFO : 1

768 ENTERING_MANAGED_PKG events! Story of my life.

Debug only

>sfdx fit:apex:log:latest -u  --debugOnly
28.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WAVE,INFO;WORKFLOW,INFO
18:56:59.180 (1181147014)|USER_DEBUG|[4]|ERROR|UserInfo.getSessionId(): 00D700000000001!ApexTestSession
18:56:59.416 (1416651819)|USER_DEBUG|[4]|ERROR|UserInfo.getSessionId(): 00D700000000001!ApexTestSession

Filtering

>sfdx fit:apex:log:latest -u  --filter USER_INFO,CODE_UNIT_STARTED
28.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WAVE,INFO;WORKFLOW,INFO
18:56:58.400 (4013418)|USER_INFO|[EXTERNAL]|005700000000001|daniel.ballinger@example.com|Pacific Standard Time|GMT-07:00
18:56:58.979 (979316201)|CODE_UNIT_STARTED|[EXTERNAL]|01q70000000HFV6|DFB.TestAccountBeforeUpdate1 on Account trigger event BeforeInsert for [new]
18:56:58.982 (982430091)|CODE_UNIT_STARTED|[EXTERNAL]|01q70000000HFVB|DFB.TestAccountBeforeUpdate2 on Account trigger event BeforeInsert for [new]
18:56:58.985 (985467868)|CODE_UNIT_STARTED|[EXTERNAL]|01q70000000blnO|DFB.AccountTrigger on Account trigger event BeforeInsert for [new]
18:56:59.108 (1108633716)|CODE_UNIT_STARTED|[EXTERNAL]|01q70000000Ti5b|DFB.ToolingTest on Account trigger event BeforeUpdate for [0010g00001YxxQ5]
18:56:59.180 (1180950117)|CODE_UNIT_STARTED|[EXTERNAL]|01q70000000H1vs|DFB.RestrictContactByName on Contact trigger event BeforeInsert for [new]

Format Shifting

>sfdx fit:apex:log:latest -u  --json
>sfdx fit:apex:log:latest -u  --csv
>sfdx fit:apex:log:latest -u  --human

The first two should still be fairly self explanatory and the latter is still intended to make reading the log easier for those that run on digesting food rather than electricity.

Installation

Most of the steps are covered in the Github repo. I found the most challenging part here to be piggybacking off the existing install of node.js and npm that lives under sfdx.

Your results may vary. It is likely safer to install your own instance of node.js. The standard disclaimer applies.

One more thing

Friday, September 8, 2017

Back to the command line - FitDx Apex debug log parser

Love it or loathe it, there are times in a developers day where you are going to find yourself at the command line. I'll leave the GUI vs command line debate to others to sort out.

My general position is they both have their strengths and weaknesses and we as developers should try and use the right tool for the job. Very much like clicks and code with Salesforce. Use them together where possible to get the most done in the least amount of effort.

Tooling shouldn't be a zero sum game.

Debug logs

Salesforce Debug logs have been a pet project area for me for some time now E.g. 2011, 2014, 2017. They form such a fundamental part of the development process but don't get a lot of love. Let me paint you a picture for a typical day in development ...

Earlier in the day something broke badly in production and you’ve only just been provided a raw 2MB text version of the debug log to diagnose the problem from. What do you do?

You can’t use any of the tooling that the Developer Console provides for log inspection on a text file. There is no way of opening it. So there will be no stack tree or execution overview to help you process a file approximately the same size as a 300 page ebook. I say approximately here because there are so many factors that could affect the size in bytes for a book. The general point is that a 2MB text file contains a lot of information that you aren't going to read in a few minutes.

The interactive debugger isn't any help for a production fault and you don't even know the steps to reproduce the problem let alone if the same thing would happen in a sandbox.

You could start combing the log file with a variety of text processing tools, or, or...

It's normally about this point that I'd direct you to the FuseIT SFDC Explorer debug log tooling which gives you:

  • (somewhat retro) GUI tooling for grouping and filtering events by category.
  • Helps highlight important events such as fatal errors and failed validations.
  • And, my current favorite, gives you a timeline view to make more sense of execution time measured in nanoseconds.

But I'm not going to cover any of that in this post. Instead we're going to cover something more experimental than the software that's been in perpetual beta for who knows how many years.

Fit DX

The FuseIT DX CLI, or FitDx in usage, is a proof of concept that I could take the debug log parser from the explorer product mentioned above and apply it directly to debug logs at the command line. I'm just putting it out there to see if there is any interest in such a thing.

You can get it right now as part of the zip download for the FuseIT SFDC Explorer.

There are certainly areas for improvement. First and foremost is the executable size. It's swollen up a fair bit from features that it doesn't expose. I'll look at whipping those out in a future release and should result in a significantly smaller package.

But enough about how big FitDx is. What's more important is how you use it.

Summary Command

If you ask sfdx for a debug log, that's exactly what you'll get. The complete, raw, unabridged debug log dumped to the command line. An experienced command line person would at this stage type out some grep regex wizardry to just show them what they wanted to see. Such is the power of the command line, but it isn't always clear where to start.

I wanted something simpler that would give you a very quick overview of what is in the log.

>sfdx force:apex:log:get -i 07L7000004G0U8kEAF -u DeveloperOrg | fitdx --summary

28.0 : 28.0 APEX_CODE,FINE;APEX_PROFILING,FINEST;CALLOUT,ERROR;DB,FINEST;SYSTEM,FINE;VALIDATION,DEBUG;VISUALFORCE,FINER;WORKFLOW,INFO
CODE_UNIT_FINISHED : 14
CODE_UNIT_STARTED : 14
CONSTRUCTOR_ENTRY : 14
CONSTRUCTOR_EXIT : 14
CUMULATIVE_LIMIT_USAGE : 14
CUMULATIVE_LIMIT_USAGE_END : 14
CUMULATIVE_PROFILING : 4
CUMULATIVE_PROFILING_BEGIN : 1
CUMULATIVE_PROFILING_END : 1
ENTERING_MANAGED_PKG : 184
EXCEPTION_THROWN : 2
EXECUTION_FINISHED : 14
EXECUTION_STARTED : 14
FATAL_ERROR : 4
LIMIT_USAGE_FOR_NS : 14
METHOD_ENTRY : 73
METHOD_EXIT : 73
SYSTEM_CONSTRUCTOR_ENTRY : 33
SYSTEM_CONSTRUCTOR_EXIT : 33
SYSTEM_METHOD_ENTRY : 165
SYSTEM_METHOD_EXIT : 165
TOTAL_EMAIL_RECIPIENTS_QUEUED : 14
USER_INFO : 14

The summary will currently give you a count for the events that are covered in the piped input. In this case I can see that there were 4 FATAL_ERROR events

Filtering

Now that I know I what I'm looking for I want to see it just those events of interest. The --filter command accepts a comma separated list of event types that you want to see. Everything else gets dropped. There is also the --debugOnly option which is a preset to filter for USER_DEBUG only.

>sfdx force:apex:log:get -i 07L7000004G0U8kEAF -u DeveloperOrg | fitdx --filter FATAL_ERROR
28.0 APEX_CODE,FINE;APEX_PROFILING,FINEST;CALLOUT,ERROR;DB,FINEST;SYSTEM,FINE;VALIDATION,DEBUG;VISUALFORCE,FINER;WORKFLOW,INFO
20:25:09.695 (698828931)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: {"filters":{"footer":{"settings":{"enable":"1","text/plain":"You can haz footers!"}}}}, Actual: {"filters":{"footer":{"settings":{"text/plain":"You can haz footers!","enable":"1"}}}}

Class.DFB.SmtpapiTest.setSetFilters: line 116, column 1
20:25:09.695 (698839161)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: {"filters":{"footer":{"settings":{"enable":"1","text/plain":"You can haz footers!"}}}}, Actual: {"filters":{"footer":{"settings":{"text/plain":"You can haz footers!","enable":"1"}}}}

Class.DFB.SmtpapiTest.setSetFilters: line 116, column 1
20:25:10.160 (1162726841)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: {"section":{"set_section_key":"set_section_value","set_section_key_2":"set_section_value_2"}}, Actual: {"section":{"set_section_key_2":"set_section_value_2","set_section_key":"set_section_value"}}

Class.DFB.SmtpapiTest.testAddSection: line 80, column 1
20:25:10.160 (1162743640)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: {"section":{"set_section_key":"set_section_value","set_section_key_2":"set_section_value_2"}}, Actual: {"section":{"set_section_key_2":"set_section_value_2","set_section_key":"set_section_value"}}

Class.DFB.SmtpapiTest.testAddSection: line 80, column 1

Format Shifting

The final set of alpha features are around changing how the debug log is presented. Options include --json, --csv, and --human. The first two should be fairly self explanatory on what the output will be. The human option was just an idea to use more column like alignment rather than vertical bars (|) to separate the elements.

In hindsight I should probably allow for multiple options at once so you can specify both the required filters and output format in one command. For the time being you can just pipe the filtered output back in.

>sfdx force:apex:log:get -i 07L7000004G0U8kEAF -u DeveloperOrg | fitdx --filter EXCEPTION_THROWN | fitdx --human
28.0                           APEX_CODE,FINE;APEX_PROFILING,FINEST;CALLOUT,ERROR;DB,FINEST;SYSTEM,FINE;VALIDATION,DEBUG;VISUALFORCE,FINER;WORKFLOW,INFO
20:25:09.695    EXCEPTION_THROWN              [116]System.AssertException: Assertion Failed: Expected: {"filters":{"footer":{"settings":{"enable":"1","text/plain":"You can haz footers!"}}}}, Actual: {"filters":{"footer":{"settings":{"text/plain":"You can haz footers!","enable":"1"}}}}
20:25:10.160    EXCEPTION_THROWN               [80]System.AssertException: Assertion Failed: Expected: {"section":{"set_section_key":"set_section_value","set_section_key_2":"set_section_value_2"}}, Actual: {"section":{"set_section_key_2":"set_section_value_2","set_section_key":"set_section_value"}}

The Forward Looking Statements

This is the part where I promise you the world with all the cool things I could potentially do in the future. Things like:

  • Direct integration as a SFDX plugin via a node.js to .NET library
  • Expose other features from the FuseIT SFDC Explorer at the command line, such as the alternative version of WSDL2Apex.
  • I've got a crazy idea for extra things like pulling apex class and trigger definitions directly from a Salesforce StackExchange question or answer and then load them directly into a newly created scratch burner org. The process could then also be reversed with the contents of the scratch org created into the required markdown. This could greatly speed up the process of asking and answering questions on the SFSE.

Friday, August 18, 2017

FuseIT SFDC Explorer 3.6.17184.1 and 3.7.17230.1 - Summer '17

The latest v3.6 release of the FuseIT SFDC Explorer is out and contains a couple of new features around Apex Debug logs.

Aaaaaannnd... because I got distracted before publishing this post, 3.7 is also out. So it's now a twofer release post.

Improvements to log parsing

Carrying on from the previous release, I've made a number of modifications to the debug log viewer.

All the calculations for duration's are now done of the underlying nanosecond ticks. This helps prevent compounding errors due to the lack of definition in C# Timespans.

The improved duration calculation is particularly important for the new grouping functionality. Take the two examples below. With the standard log you can get 200 CODE_UNIT_STARTED events for the validation of each record in a transaction (plus the corresponding 200 CODE_UNIT_FINISHED events). With the new "Group Recurring Events" button in the tool bar any repeating events of the same type will be collapsed into a single node with a summary.

Before

After

While still on the topic of the Apex Log Tree View, DML operations now have a basic icons to indicate which variant of Insert, Update, Upsert, or Delete operation they are. Trigger, Validation, and Workflow have consistent color coding between the Tree View and the Timeline.

Auto build a Metadata package

There is a new option on the Metadata Deploy tab under "Deploy Selected Files" called "Compare File Hashes". As per the name, it will do a CRC32 diff of the body of Apex classes, triggers and visualforce pages between the local file system and the connected Salesforce org. If anything is different it gets added to the current package ready for deployment.

If it turns out the local file is the one that should be updated there is a context menu option to update the local file.

Colored logging

Both the Metadata Deployment results and test method error results now include some basic color.

Salesforce DX CLI integration

If you have the Salesforce DX CLI installed (and in the path) you can use it to manage org logins. It might take a moment after pressing "Refresh Orgs" for the list to come back. Once it does, just select an org and press login.

Other changes 3.6

  • Log Tree view. Color code Trigger, Validation, and Workflow events. Open debug log from File. Toggle Timeline and Treeview display.
  • Highlight FLOW_ELEMENT_ERROR messages in the log.
  • Handle log highlighting for Fine, Finer, and Finest logging levels. Provide links for ids for the active org.
  • Optionally display scale on the log. Highlight VALIDATION_FAIL events.
  • Highlight Exception and skipped/maxlog events in the Log Timeline.
  • When parsing a log, identify the log levels applied (if present) in the footer.
  • Attempt to determine if an ApexClass contains tests. Use this to drive direct running tests cases from the class.
  • Improve performance of building the EntityTree from sObject describe results. Especially for orgs with a large number of custom objects and settings.

Other changes 3.7

  • Add optional allowExistingSObjectsWithoutId="true" to the binding configuration element to allow sObjects to be created with a null Id. Typically this isn't allowed as the ID is used to control insert/update operations and to identify relationship types. This setting can be used for more basic SOQL queries where the results won't be subsequently used for DML.
  • Highlight CALLOUT_REQUESTs in the timeline as they often take up large chunks of time.
  • Fix for updating available metadata types with Session change.
  • Improve SessionId validation pre login
  • When exporting results, give the user the choice of folder to export to.
  • Handle SOQL Aggregate Results that return only a single value
  • Improve IDEWorkspace integration. Allow for switching of workspaces.
  • Wsdl2Apex: Handle case where the Schema TargetNamespace is missing
  • Perform Metadata Deploy Hash on Apex Pages. Option to refresh local metadata from Server.

Thursday, February 2, 2017

FuseIT SFDC Explorer 3.5.17023.3 - The more logging edition

The latest v3.5 release of the FuseIT SFDC Explorer is out and contains a couple of new features around Apex Debug logs.

The Challenge and Premise

Understanding an Apex log can require understanding events occurring at vastly different time scales.

At the very fine end, each event timestamp is supplemented with the elapsed time in nanoseconds since the start of the request. At the other end is the duration of the entire log itself, which can span seconds or even minutes of execution time.

By my figuring that is 3 orders of magnitude difference.

To try and put that into perspective...

DurationExample (using something very fast)
1 nanosecondLight travels 30 centimeters (12 inches)
1 minuteLight travels 17,990,000 kilometers (11,180,000 miles)

So while in a nanosecond reflected light could travel from your hand to your eyes. In a minute it could travel between the earth and moon 46 times. Or around the circumference of the earth almost 450 times. Yes, I'm playing a bit fast and loose using the speed of light in a vacuum, but you get the general gist of how vastly different a nanosecond duration is to seconds or minutes. It takes one billion nanoseconds to make a second, and that is a very big number when you are dealing with log events.

That's enough of a detour trying to make the point that we are dealing with periods of time at vastly different scales. I'll now take a similarly cavalier approach to how I'm going to address this challenge.

The human brain processes visual data 60,000 times faster than text

That's an awesome quote for what I'm trying to demonstrate, except it doesn't seem to be backed up by any actual research. Let's roll with it anyway.

When looking at a log it is useful to see how an events timing relates to those events immediately around it and where it sits in the overall transaction. To that end, I've started plotting the debug log events out in a timeline view under the core log.

"But Daniel" you say, "The Developer Console Log Inspector has had the Execution Overview for yonks, why do we need another log viewer?"
To which I reply, "Are you British? Because yonks sounds like a unit of time you would hear about when watching something from the BBC." and "How on earth did you include a hyperlink in speech? That's some next level DOM injection right there."

My primary reason for making a log parser has always been that the Developer Console is of no use to you if you can't load the log of interest into it. Logs don't just come from directly in the console. They get emailed to you in the "Developer script exception" emails, or from a well meaning admin. They get saved to disk and then examined days after the fact. In cases like these the Developer Console can't help you at all.

While the FuseIT SFDC Explorer will happily load logs captured directly in the org, it can also have them pasted straight in and parse them all the same.

Debug log Timeline view

I've deliberately tried to avoid making a carbon copy of the existing Developer Console functionality. What would be the point? Instead I've looked for a way to visualize all the events in one timeline view. Of course, with some things occurring so closely together the finer details get lost. Where I've found it useful is:

  • in identifying clumps of events,
  • where an event sits in relation to the rest of the log, and
  • to jump to events of importance quickly.

Let's look at the timeline the came out of a test class run. The log had reached the 2MB limit and covered 13,000 events over 39,500 lines. One of the test methods failed, and we want to hone in on that in the log.

Note the bang icon in the middle of the timeline. Clicking on that takes use straight to the FATAL_ERROR in question.

Debug log Tree view

The Developer Console provides both the Stack Tree and Execution Stack for the currently selected event. I've always found these a little odd to be honest in the slight disconnect with the actual log events. E.g. USER_DEBUG becomes "debug".

Let's start with something simple. Execute anonymous for a for loop that does 8 iterations of a debug statement.

for(integer i = 0; i < 8; i++) {
    System.debug(i);
}

The Developer Console shows the 8 debug statements. All with a duration of 0.01 ms with the exception of one that took 0.06 ms. The Execution Stack shows similar details for the currently selected event.

What can we see from the same code in the FuseIT SFDC Explorer? That depends on how you filter the log.

If you keep the default settings with opening the log with [Prefilter Log] enabled that various events like SYSTEM_METHOD_ENTRY and SYSTEM_METHOD_EXIT will be completely omitted. This makes the log easier to work with, but mucks with the event durations. With logs you can easily tell when something happened, but to get an accurate duration you need a BEGIN/END or ENTRY/EXIT pair of events. Hence the duration of the first USER_DEBUG seems excessively long as it was measured from the prior event.

If you keep all the log events in then you get a tree with very similar figures. The main difference being that you and see the ENTRY/EXIT pairs.

Real World example

Have a look at the Apex CPU time limit exceeded in tidy trigger pattern question on the Salesforce StackExchange without skipping down to the answer (NO CHEATING). Grab the apex log they attached and try and figure out what the likely cause of the CPU limit exception is.


Read on when you've figured it out...


Here's what I can tell you from the log timeline.

Notice the recurring pattern of red (before update triggers), green (validation), orange (after update triggers), and purple (workflow). As per the question they are updating 2956 Account records. So the records are processed in batches of 200. You can also see where the skipped log section is (exclamation mark about 3/4 away along) and the FATAL_ERRORs at the end of the log.

If you then look at one of those batches in the tree view I can see that the triggers themselves are relatively quick and the longest duration from any of the code units is for the workflow. Definitely the smoking gun to investigate first.

I like to think that the combination of the timeline and treeview made isolating the problem much easier. Especially considering the Developer Console wasn't available in this case.

The forward looking statements

It's still very much a work in progress.

The biggest thing that stands out to me at the moment is the color coding for events. I want similar events to have similar colors. Important events to stand out and less important events to fade away. The CODE_UNIT color categories not to conflict with the event colors. This is a tricky thing to do when you struggle to name more than the standard 16 colors supported with the Windows VGA palette

The accuracy of the duration measurements is important. In the current 3.5 release the elapsed times were all converted to C# Timespans, which lacked the nanosecond accuracy. In the next release I'll do all the calculations from the raw nanoseconds and convert to Timespans only when needed for display.

Wednesday, December 14, 2016

FuseIT SFDC Explorer 3.4.16349.2

The latest v3.4 release of the FuseIT SFDC Explorer is out and contains a number of new features.

SOQL Queries with nested sub queries

Previously if you did a SOQL query with a nested related query I'd flatten out the results for display. This was less than ideal as all the sub records would get mushed together. Yuck!

Compare this with the developer console where JSON is the preferred way to handle the nested data.

Using the "Flat Display" table button will now toggle between the old behavior and providing a link to popup the nested results.

Basic IDE Workspace support

When you first connect to an Org a check will be made for existing IDEWorkspace records for the authenticating user. This can be used to restore the last anonymous apex code or previous SOQL queries.

Tabular Report Viewer

There is now a basic report viewer. The selected report can be exported to CSV, the clipboard, or Excel's XLSX format. I've only really tested it against tabular reports so far. When exported to Excel both the cell value and label will be maintained.

It's still early days for this feature. There are lots of improvements I could do around maintaining the field data types on the transition to Excel, such as DateTimes, Booleans, picklists. I could also add an option to nominate an ID column to be used for sorting that would then allow you to access more than 2000 records.

Do let me know if this is an area that would be useful to extend.

Asynchronous loading of org metadata

I'd noticed that the login time was getting successively slower. Turns out it was getting expensive to describe the sObject metadata as the number of sObjects grew in each org. They have to batched per 100. I've switched to loading the metadata asynchronously on initial login. It might take a moment before all the sObjects are available.

Pod Status and Release version

After a Session is established a quick check will be made for the current pod status and patch version.

Other changes

  • Improved Tooling API Metadata exploring by caching the describesObject results.
  • In Tooling API SOQL results, directly update values in the GridView
  • Selecting Id's or the Session ID from the Status Bar will give an option to copy the value to the clipboard.
  • Improvements for manual package creation with Metadata Deployment. You can now remove previously added nodes, or diff them with the target org.
  • Option to filter an Apex log to just rows that match the search term.

Friday, September 30, 2016

FuseIT SFDC Explorer 3.3.16274.7

The latest v3.3 release of the FuseIT SFDC Explorer is out and contains a number of new features. Just in time for Dreamforce '16.

Metadata Deploy

Select a folder to monitor for changes (1). Anything that changes in that folder and is a supported metadata type is added directly to the package.

Select a folder to scan for files modified today (2). Finds any supported metadata types that were added today and adds them to the package.

Redeploy the most recent package (3). If you last deployed from a collection of selected files it will rebuild the package from those and deploy them.

SOSL query support

The SOQL Query tab now doubles as a SOSL query tab (no syntax highlighting yet). You can also export the results to a CSV or the clipboard as with SOQL.

Code Coverage

On the code coverage tab the Percent column has some color coding to indicate if you are hitting the minimum 75% for that class. The individual selected classes is also shown plus an org wide coverage at the top.

The green double arrow to the right of the classes code coverage will attempt to find all the test cases that contribute the the coverage of that class. Then it queues those tests up to run.

Note that as of the time of writing there is a bug in the SOAP version of the Tooling API that is preventing individual line coverage results from being returned.

Apex test execution

If Max Failures is set to a number greater than -1 it will stop after the specified number of test case failures in an asynchronous run.

Individual Entity Viewer

When viewing an individual record by ID the field metadata will be used to expand the property grid and show all the accessible fields. Note that I'm seeing some oddities with the Entity Viewer and sometimes need to toggle between the Categorized and Alphabetical views to get it to render. It might just be something with my display drivers.

Other changes

  • Detect and highlight a "Skipped X bytes of detailed log" message in the debug log
  • WSDL2Apex: Handle class name conflicts within a namespace.
  • WSDL2Apex: Add warning for "INVALID_FIELD_FOR_INSERT_UPDATE - Number of parameters exceeds maximum: 32" - Include names for elements in warnings.
  • WSDL2Apex: Improve error handling if WSDL schema element is missing type attribute
  • WSDL2Apex: ensure enum name starts with a letter. It is not allowed to start with the number in Apex.