Including source code in your application build

An application that demonstrates a component suite often serves as both a showcase and a learning tool. It provides an interactive way to explore the functionality, design, and capabilities of a set of UI components or features. What makes it particularly valuable is its ability to display its own source code alongside the demo, offering developers direct insight into how the components are implemented and used. This dual-purpose approach empowers users to not only evaluate the components but also understand and adopt them more efficiently in their own projects.

The easiest way to achieve this is actually very simple. First, edit your csproj file and add an <ItemGroup> section. For each file you want to include, add an <EmbeddedResource> node inside the <ItemGroup> like so…

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

	<PropertyGroup>
		<TargetFramework>net9.0</TargetFramework>
		<Nullable>enable</Nullable>
		<ImplicitUsings>enable</ImplicitUsings>
	</PropertyGroup>

	<ItemGroup>
		<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.0" />
		<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.0" PrivateAssets="all" />
	</ItemGroup>

	<!-- Add the following -->
	<ItemGroup>
		<EmbeddedResource Include="Pages\Home.razor"></EmbeddedResource>
	</ItemGroup>

</Project>

Then you can access the source code like so…

private static string ReadContents(string name)
{
   using Stream stream = typeof(Home).Assembly.GetManifestResourceStream(name)!;
   using var reader = new StreamReader(stream);
   return reader.ReadToEnd();
}

For example, if you have a Blazor app you can do this…

@page "/"

<PageTitle>Home</PageTitle>

<p>
    The source code for this page is
</p>
<code>
    <pre>
        @Contents
   </pre>
</code>


@code {
    private string Contents = "";

    protected override void OnInitialized()
    {
        base.OnInitialized();
        Contents = ReadContents("BlazorApp56.Pages.Home.razor")!;
    }

    private static string ReadContents(string name)
    {
        using Stream stream = typeof(Home).Assembly.GetManifestResourceStream(name)!;
        using var reader = new StreamReader(stream);
        return reader.ReadToEnd();
    }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *