Edit

Create packages for the Package Deployer tool

Package Deployer lets administrators deploy packages on Microsoft Dataverse instances. A Package Deployer package can consist of any or all of the following:

  • One or more Dataverse solution files.
  • Flat files or exported configuration data file from the Configuration Migration tool. For more information about the tool, see Move configuration data across instances and organizations with the Configuration Migration tool.
  • Custom code that can run before, while, or after the package is deployed to the Dataverse instance.
  • HTML content specific to the package that can display at the beginning and end of the deployment process. This content can be useful to provide a description of the solutions and files that are deployed in the package.

Note

There's another package type called a plug-in package. That kind of package is for plug-in dependent assemblies and has no relationship with Package Deployer packages.

Prerequisites

  • Ensure that you have all the solution and other files ready that you want to include in the package.
  • Visual Studio 2019 or later, or Visual Studio Code.

Process overview

To create a Package Deployer package, complete the following steps:

  • Create a Visual Studio or MSBuild project
  • Add solutions and other files to the project
  • Update provided HTML files (optional)
  • Specify configuration values for the package
  • Define custom code for the package
  • Build and deploy the package

This article describes these steps in detail.

Create a package project

First, create a Visual Studio or MSBuild project for the package. To create the project, install one of two available tool extensions on your development computer. If you use Visual Studio Code, install Microsoft Power Platform CLI. If you use Visual Studio 2019 or later, install Power Platform tools for Visual Studio.

To learn how to create a project by using your desired tool extension, select the appropriate tab in the following section. Both tools output the project in a similar format.

Run the pac package init command to create the initial package. For more information, see pac package.

pac package init help
pac package init --outputDirectory DeploymentPackage

The CLI output includes the following folders and files. The name DeploymentPackage is used here as an example.

C:.
└───DeploymentPackage
    │   DeploymentPackage.csproj
    │   PackageImportExtension.cs
    │
    └───PkgAssets
            ImportConfig.xml
            manifest.ppkg.json

In the created project, locate the ImportConfig.xml configuration file in the PkgAssets folder and the PackageImportExtension.cs file. You'll modify these files as described later in this article.

Add package files

After you create a package project, you can begin adding solutions and other files to that project.

When you use the CLI, you can add external packages, solutions, and references to your package project by using one of the add subcommands. Enter pac package help to see the list of subcommands. Let's add a solution to our package.

> pac package add-solution help

Commands:
Usage: pac package add-solution --path [--import-order] [--skip-validation] [--publish-workflows-activate-plugins] [--overwrite-unmanaged-customizations] [--import-mode] [--missing-dependency-behavior] [--dependency-overrides]

> cd .\DeploymentPackage\
> pac package add-solution --path ..\TestSolution_1_0_0_1_managed.zip

The item was added successfully.

Configure the package

Define the package configuration by adding information about your package in the ImportConfig.xml file in the project. For an example and descriptions of the valid elements and attributes to use, see ImportConfig Reference.

Add custom code

You can add custom code that runs before, during, and after the package imports into an environment. To add custom code, follow these instructions:

  1. Edit the PackageTemplate.cs or PackageImportExtension.cs file in the project's root folder.

  2. In the C# file, you can:

    1. Enter custom code to run when the package initializes in the override method definition of InitializeCustomExtension.

      Use this method to let users use the runtime parameters while running a package. As a developer, you can add support for any runtime parameter to your package by using the RuntimeSettings property as long as you have code to process it based on the user input.

      For example, the following sample code enables a runtime parameter called SkipChecks for the package that has two possible values: true or false. The sample code checks if the user specifies any runtime parameters while running Package Deployer (either by using the command line or PowerShell), and then processes the information accordingly. If the user doesn't specify a runtime parameter while running the package, the value of the RuntimeSettings property is null.

      public override void InitializeCustomExtension()  
      {
        // Validate the state of the runtime settings object.  
        if (RuntimeSettings != null)  
        {  
            PackageLog.Log(string.Format("Runtime Settings populated.  Count = {0}",
                RuntimeSettings.Count));  
            foreach (var setting in RuntimeSettings)  
            {  
                PackageLog.Log(string.Format("Key={0} | Value={1}", setting.Key, 
                    setting.Value.ToString()));  
            }  
      
            // Check to see if skip checks is present.  
            if ( RuntimeSettings.ContainsKey("SkipChecks") )  
            {  
                bool bSkipChecks = false;  
                if (bool.TryParse((string)RuntimeSettings["SkipChecks"], out bSkipChecks))  
                    OverrideDataImportSafetyChecks = bSkipChecks;  
            }  
        }  
        else
        {
            PackageLog.Log("Runtime Settings not populated");
        }  
      } 
      

      This code enables the administrator to use the command line or the Import-CrmPackage cmdlet to specify whether to skip the safety checks while running the Package Deployer tool to import the package. For more information, see Deploy packages using Package Deployer and Windows PowerShell.

    2. Enter custom code to run before the solutions import in the override method definition of PreSolutionImport. Use this method to specify whether to maintain or overwrite customizations while updating the specified solution in a target Dataverse instance, and whether to automatically activate plug-ins and workflows.

    3. Use the override method definition of RunSolutionUpgradeMigrationStep to perform data transformation or upgrade between two versions of a solution. This method runs only if the solution you're importing is already present in the target Dataverse instance.

      This function expects the following parameters:

      Parameter Description
      solutionName Name of the solution
      oldVersion Version number of the old solution
      newVersion Version number of the new solution
      oldSolutionId GUID of the old solution.
      newSolutionId GUID of the new solution.
    4. Override the method OverrideSolutionImportDecision to return a UserRequestedImportAction enum that controls whether the import of a solution is skipped, updated, or upgraded (the default).

      public override UserRequestedImportAction OverrideSolutionImportDecision(
        string solutionUniqueName, Version organizationVersion,
        Version packageSolutionVersion, Version inboundSolutionVersion,
        Version deployedSolutionVersion, ImportAction systemSelectedImportAction )
      {
        return systemSelectedImportAction == 
            ImportAction.Import ? UserRequestedImportAction.ForceUpdate
            : base.OverrideSolutionImportDecision(solutionUniqueName, organizationVersion,
            packageSolutionVersion, inboundSolutionVersion, deployedSolutionVersion,
            systemSelectedImportAction);
      }
      
    5. Enter custom code to run before the solution import completes in the override definition of the BeforeImportStage method. The tool imports the sample data and some flat files for solutions specified in the ImportConfig.xml file before the solution import completes.

    6. Override the currently selected language for configuration data import by using the override method definition of OverrideConfigurationDataFileLanguage. If the specified locale ID (LCID) of the specified language isn't found in the list of available languages in the package, the default data file imports.

      You specify the available languages for the configuration data in the <cmtdatafiles> node in the ImportConfig.xml file. You specify the default configuration data import file in the crmmigdataimportfile attribute in the ImportConfig.xml file.

      Skipping data checks (OverrideDataImportSafetyChecks = true) can be effective here if you're sure that the target Dataverse instance doesn't contain any data.

    7. Enter custom code to run after the import completes in the override definition of AfterPrimaryImport method. The tool imports the remaining flat files that weren't imported earlier, before the solution import started.

    8. Change the default name of your package folder to the package name that you want. To do so, rename the PkgFolder or PkgAssets folder in the Solution Explorer pane, and then edit the return value under the GetImportPackageDataFolderName property.

      public override string GetImportPackageDataFolderName  
      {  
          get  
          {  
              // WARNING this value directly correlates to the folder name in Solution 
              // Explorer where the ImportConfig.xml and sub content is located.  
              // Changing this name requires that you also change the correlating name
              // in Solution Explorer.
              return "PkgFolder";  
          }  
      }  
      
    9. Change the package name by editing the return value under the GetNameOfImport property.

      public override string GetNameOfImport(bool plural)  
      {  
          return "Package Short Name";  
      }  
      

      This returned value is the name of your package that appears on the package selection page in the Dynamics 365 Package Deployer wizard.

    10. Change the package description by editing the return value under the GetImportPackageDescriptionText property.

      public override string GetImportPackageDescriptionText  
      {  
          get { return "Package Description"; }  
      }  
      

      This returned value is the package description that appears alongside the package name on the package selection page in the Package Deployer wizard.

    11. Change the package long name by editing the return value under the GetLongNameOfImport property.

      public override string GetLongNameOfImport  
      {  
          get { return "Package Long Name"; }  
      }  
      

      The package long name appears on the next page after you select the package to install.

  3. The package also has access to the following functions and variables:

    Name Type Description
    CreateProgressItem(String) Function Creates a new progress item in the user interface (UI).
    RaiseUpdateEvent(String, ProgressPanelItemStatus) Function Updates the progress created by the call to CreateProgressItem(String).

    ProgressPanelItemStatus is an enum with the following values:

    Working = 0
    Complete = 1
    Failed = 2
    Warning = 3
    Unknown = 4
    RaiseFailEvent(String, Exception) Function Fails the current status import with an exception message.
    IsRoleAssociatedWithTeam(Guid, Guid) Function Determines if a role is associated with a specified team.
    IsWorkflowActive(Guid) Function Determines if a specified workflow is active.
    PackageLog Class Pointer A pointer to the initialized logging interface for the package. The package uses this interface to log messages and exceptions to the package log file.
    RootControlDispatcher Property A dispatcher interface that your control uses to render its own UI during package deployment. Use this interface to wrap any UI elements or commands. Check this variable for null values before using it, as it might not be set to a value.
    CrmSvc Property A pointer to CrmServiceClient class that allows a package to address Dynamics 365 from within the package. Use this pointer to execute SDK methods and other actions in the overridden methods.
    DataImportBypass Property Specify whether Dynamics 365 Package Deployer skips all data import operations such as importing Dataverse sample data, flat file data, and data exported from the Configuration Migration tool. Specify true or false. Default is false.
    OverrideDataImportSafetyChecks Property Specify whether Dynamics 365 Package Deployer bypasses some of its safety checks, which helps improve the import performance. Specify true or false. Default is false.

    Set this property to true only if the target Dataverse instance doesn't contain any data.
  4. Save your project. The next step is to build the package.

Build and deploy

The following sections describe how to build and deploy a package.

Build

The following sections describe how to build your package, depending on which tool you're using.

To build a package created with the CLI, you can load the .csproj file into Visual Studio, but you can also use the dotnet command and MSBuild. The following example assumes the working directory contains the *.csproj file.

> dotnet publish

DeploymentPackage -> C:\Users\peter\Downloads\DeploymentPackage\bin\Debug\DeploymentPackage.1.0.0.pdpkg.zip

You can optionally view the details of the built package.

> pac package show --package .\bin\Debug\DeploymentPackage.1.0.0.pdpkg.zip

Your package consists of the following files under the *<Project>*\Bin\Debug folder:

  • <PackageName> folder: The folder name matches the name you chose for your package folder in step 2.g of the Add custom code section. This folder contains all solutions, configuration data, flat files, and the contents for your package.

Note

You might see a .NET folder (for example, net472) that contains a pdpublish folder. Your DLL and other project files are in that pdpublish folder.

  • <PackageName>.dll: The assembly contains the custom code for your package. By default, the name of the assembly matches your project name.

Deploy

After you create a package, deploy it on the Dataverse instance by using the Package Deployer tool, Windows PowerShell, or a CLI command.

  • To deploy by using the Package Deployer tool, first download the tool as described in Dataverse development tools. Next, follow the detailed information on package deployment in the article Deploy packages using Package Deployer or Windows PowerShell.

  • To deploy by using the CLI, use the pac package deploy command.

    > pac package deploy --package .\bin\Debug\DeploymentPackage.1.0.0.pdpkg.zip
    

    Note

    To deploy a package to a target environment by using the CLI, you must first set up an authentication profile and select an organization. For more information, see pac auth create and pac org select.

Best practices

Listed below are a few best practice tips to follow when working with Package Deployer packages.

Creating packages

When creating packages, developers must:

  • Ensure that package assemblies are signed.

Deploying packages

When deploying packages, Dataverse administrators must:

  • Insist on signed package assemblies so that you can track an assembly back to its source.
  • Test the package on a preproduction instance, preferably a mirror image of the production instance, before running it on a production instance.
  • Back up the production instance before deploying the package.

See also

Solution Packager tool