Skip to content

Samples

Richard Stanton edited this page Aug 9, 2024 · 5 revisions

These are some basic samples using the model and serializers.

Convert a solution file to a .slnx solution file.

private static async Task ConvertToSlnxAsync(string filePath, string slnxFilePath, CancellationToken cancellationToken)
{
    // See if the file is a known solution file.
    ISolutionSerializer? serializer = SolutionSerializers.GetSerializerByMoniker(filePath);
    if (serializer is null)
    {
        return;
    }

    try
    {
        SolutionModel solution = await serializer.OpenAsync(filePath, cancellationToken);
        await SolutionSerializers.SlnXml.SaveAsync(slnxFilePath, solution, cancellationToken);
    }
    catch (SolutionException)
    {
        // There was an unrecoverable syntax error reading the solution file.
        return;
    }
}

Read each project and get project build configurations

private static void ReadEachProject(SolutionModel solution)
{
    // Pick the first configuration in the solution.
    string buildConfiguration = solution.BuildTypes[0];
    string buildPlatform = solution.Platforms[0];

    foreach (SolutionProjectModel project in solution.SolutionProjects)
    {
        string projectFilePath = project.FilePath;

        // Find the project configuration for the solution build configuration and platform.
        (string? buildType, string? platform, bool build, bool deploy) = project.GetProjectConfiguration(buildConfiguration, buildPlatform);

        if (buildType is null || platform is null)
        {
            Console.WriteLine("Project {0} missing a configuration for {1}|{2}.", projectFilePath, buildConfiguration, buildPlatform);
            continue;
        }

        if (build)
        {
            Console.WriteLine("Project {0} is set to build as {1}|{2}.", projectFilePath, buildType, platform);
        }

        if (deploy)
        {
            Console.WriteLine("Project {0} is set to deploy as {1}|{2}.", projectFilePath, buildType, platform);
        }
    }
}

Add a project with an optional solution folder

private static void AddProject(SolutionModel solution, string? solutionFolder, string projectFilePath)
{
    SolutionFolderModel? parentSolutionFolder = null;
    if (solutionFolder is not null)
    {
        parentSolutionFolder = solution.AddFolder(solutionFolder);
    }

    // If the project type can be determined from the file extension, the project type name is optional.
    // If it cannot, a built-in name can be used, such as "Website" for a website project.
    // If it is not a built-in name, a project type can be added to the solution.
    // Finally the project type id guid can be used.
    string? projectTypeName = null;

    SolutionProjectModel newProject = solution.AddProject(projectFilePath, projectTypeName, parentSolutionFolder);
}