When developing, there are often things that you repeat on a regular basis. In order to speed up development, it can be helpful to have portions of code that are available for quick access.
With Visual Studio, it is possible to put together code snippets with templated variables, which allows for quick creation of essential portion of code. For example, when developing CRM solutions, I very frequently find myself writing Query Expressions that are very similar in format. So I’ve created a template of these to use, which can be activated very simply.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>QueryExpression</Title>
<Description>Adds basic query expression template</Description>
<Shortcut>qe</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[QueryExpression $qe$ = new QueryExpression("$logicalName$") { NoLock = true };
EntityCollection $coll$ = sdk.RetrieveMultiple($qe$);$end$]]>
</Code>
<Declarations>
<Literal>
<ID>qe</ID>
<ToolTip>Replace with the name of the QueryExpression.</ToolTip>
<Default>qe</Default>
</Literal>
<Literal>
<ID>coll</ID>
<ToolTip>Replace with the name of the EntityCollection.</ToolTip>
<Default>coll</Default>
</Literal>
<Literal>
<ID>logicalName</ID>
<ToolTip>Replace with the logical name of the entity to retrieve.</ToolTip>
<Default>account</Default>
</Literal>
</Declarations>
</Snippet>
</CodeSnippet>
</CodeSnippets>
A snippet is very quick and easy to set up. A complete guide can be found here: https://docs.microsoft.com/en-us/visualstudio/ide/walkthrough-creating-a-code-snippet but I’ll provide a quick overview.
In the definition, the attributes of the snippet are set. This includes the Title/name, description and designated shortcut.
Templated variables can be created in the declarations node and then included by surrounding them with ‘$’ characters, as shown above. The variables can then be customized under ‘Declarations’, to specify the ID, Tooltip, and Default.
Note: $end$ is added to remove the extra line break at the start of the snippet.
Use
Once set up, the snippet is very easy to use. Simply type the specified shortcut – in this case qe – and press the tab key to expand the snippet.
Once used, the templated variables can be tabbed through and changed just like out of the box Visual Studio code snippets.