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.
In a previous blog, I wrote about how you can use Visual Studio snippets to allow for quick creation of code that is used on a regular basis.
Another way to accomplish this is through the use of Visual Studio item templates. A template, as opposed to a snippet, can allow you to create the overall structure of your code. A good example of when this is useful is when developing plugins for CRM. Often, plugins in CRM follow a certain structure or process:
• Obtain IPluginExecutionContext
• Obtain IOrganizationServiceFactory
• Obtain IOrganizationService
• Obtain needed parameters from context
• Execute plugin logic
If you are following these steps the entire time, it doesn’t make sense to write them out manually each time. This is where templates come in. It’s possible to write the general structure of the file, including using statements and supplementary methods.
Templates are quite quick to set up. A complete guide can be found here: https://docs.microsoft.com/en-us/visualstudio/ide/how-to-create-item-templates but I’ll provide a quick overview. For the purposes of this example, I’ll demonstrate how to create a plugin template.
I’ve included the sample code for a plugin template here, which includes initialising the IOrganizationService and ITracingService, and obtaining an entity from the context.
public class $safeitemname$ : IPlugin
public void Execute(IServiceProvider serviceProvider)
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(null);
ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
Entity target = context.InputParameters["Target"] as Entity;
// Logic goes here...
Once set up, the template is very easy to use. In a project, select add item, then select the template for use. The template will automatically draw the variables from the creation window, including name and namespace.
The end result is shown below: