340: With George Francis

Chris gets to chat with George Francis, an incredible digital artist in the generative art space as well as educator and all-around developer. George has been all over the place lately, producing really outstanding work (CSS-Tricks uses a Houdini paint worklet from George in the header and footer). Not only does George make art that has that little special something that turns heads, he helps you do it too by sharing all the tools and techniques he uses in blog posts.

Time Jumps

00:28 Guest introduction

01:35 Do you like the term Generative Code?

03:27 Limiting the randomness

06:04 How do I random blob?

10:52 Sponsor: Netlify

12:22 Which blobs get popular on CodePen

16:00 Working with Houdini

23:08 What goals do you have with your work?

26:49 NFTs and generative code

29:46 Tell us about your day job

Sponsor: Netlify

Netlify has used the slogan “Static without limits” — which I really like. It’s useful to think of Netlify as a static file host as the foundation. That’s what Jamstack is, after all. But it doesn’t mean that you are limited in what you can build. You can make a site that is every bit dynamic as any other architecture out there, and Netlify not only encourages it but will help you do it with features like hosted cloud functions.

The post 340: With George Francis appeared first on CodePen Blog.

Automatically add #Sedo verification to a batch of domain names using #NameCheap #API

If you are listing domains on Sedo, it’s likely that you have a number of domains, and perhaps instead of going through the process of manually adding the CNAME record to every domain, you can use NameCheap’s API in C# to automatically add CNAME records.

This is a follow-on to the previous blog post, shown below; Classes mentioned in this post will not be repeated, so you should follow this first;

Given a list of domains in a text file (one domain per line), add this to the project with the build action “copy always”.

var domains = File.ReadAllLines(“domainList.txt”);
foreach (var domain in domains)
{
Console.WriteLine(domain);
var domainTld = Regex.Match(domain, @”.w+$”).Value;
var domainWithoutTld = domain.Replace(domainTld, “”);
domainTld = domainTld.Substring(1);
var hosts = GetHostsFromDomain(domainWithoutTld, domainTld);
Thread.Sleep(TimeSpan.FromSeconds(1));
hosts.Add(new HostRecord { Name = “***ID***”, Type = “CNAME”, Value = “verify.sedo.com” });
Thread.Sleep(TimeSpan.FromSeconds(1));
SetHostRecords(domainWithoutTld, domainTld, hosts);
Thread.Sleep(TimeSpan.FromSeconds(1));
}

Where evidently ***ID*** is replaced with your own personal ID from Sedo. The one second delays are to help prevent throttling, which the NameCheap API uses to prevent abuse.

And, if you’re interested, this is the list of domains that is going on sale;

webserverdown.com
vatapi.co.uk
universaltravelsearch.com
u2fapi.com
tweetjs.com
tempemailaddress.com
resxtranslate.com
printfromwindowsphone.com
printfromipad.com
outsourcetranslation.com
omadataobjects.com
listoftaxis.info
listofpubs.info
listofhotels.info
listofhauliers.info
listofestateagents.info
listofdevelopers.info
listofcardealers.info
listofbanks.info
javatiger.com
installipa.com
gotoeuro.net
freetextuk.com
freebiesms.com
freebiebitcoin.com
electoralrollapi.com
domaindeflect.com
dns-js.com
derrycreativescollective.com
createfreeapp.com
burnersms.com
airportdelays.org

Implementing Content Security Policy (CSP) in ASP.NET Core

This post is about implementing content security policy in ASP.NET Core. Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware – Content Security Policy (CSP) MDN

A primary goal of CSP is to mitigate and report XSS attacks. XSS attacks exploit the browser’s trust in the content received from the server. Malicious scripts are executed by the victim’s browser because the browser trusts the source of the content, even when it’s not coming from where it seems to be coming from. CSP helps developers to configure the URL of the resources, and if some other resource which is not part of the configuration won’t be loaded into the browser. CSP also helps on mitigating packet sniffing attacks. Content Security Policy can be configured in ASP.NET Core with the help of Content-Security-Policy header.

Here is an example of the CSP Header of facebook.com

In ASP.NET Core, you can create middleware to set the header to http response, here is a minimal middleware to do this. You need to add this code to the Configure() method in Startup.cs before the UseEndpoints method.

app.Use(async (context, next) =>
{
context.Response.Headers.Add(“Content-Security-Policy”, “default-src ‘self’;”);
await next();
});

And when you run the app you will be able to see everything is working as expected – since the default template is loading everything from the app only. Let us modify the code and instead of loading the Bootstrap resources from local move them to CDN and will verify it. When loading any scripts or styles from CDN, browser will not load them, because you are configured the content security policy to load resources from the app only.

Since I configured the CSP Header to load resources from self which is the app, browser is not loading any resources from CDN. You can fix this by adding the CDN URL in the CSP Header – like this.

app.Use(async (context, next) =>
{
context.Response.Headers.Add(“Content-Security-Policy”, “default-src ‘self’ cdn.jsdelivr.net;”);
await next();
});

You can find more details about CSP and its various configuration in Content Security Policy (CSP) MDN. And you can validate your CSP Headers in SecurityHeaders.com. If you’re building a new application, you can configure CSP easily and write code adhering the CSP rules. But if you’re trying to apply CSP in an existing website it is quite overwhelming because most of the code – inline styles, scripts, events and all may not work. To avoid this issue, you can use Content-Security-Policy-Report-Only header with the report URL parameter – it will not ignore the script or resource instead it will display the error to the report URL.

app.Use(async (context, next) =>
{
context.Response.Headers.Add(“Content-Security-Policy-Report-Only”, “default-src ‘self'”);
await next();
});

Here is the screenshot of the app running with Content-Security-Policy-Report-Only header – It is loading the resources and logging the errors in the browser console as well.

You can configure an endpoint if you would like you to store the CSP violations in Database or tools like Application Insights. First you need to create a HTTP Post endpoint and you can write logic to store the information in database. Here is the implementation.

[HttpPost(“cspreport”)]
public IActionResult CSPReport([FromBody] CspReportRequest cspReportRequest)
{
_logger.LogInformation(@$”CSP Violation: {cspReportRequest.CspReport.DocumentUri},
{cspReportRequest.CspReport.BlockedUri}“);
return Ok();
}

And here is the CspReportRequest model class.

public class CspReportRequest
{
[JsonPropertyName(“csp-report”)]
public CspReport CspReport { get; set; }
}

public class CspReport
{
[JsonPropertyName(“document-uri”)]
public string DocumentUri { get; set; }

[JsonPropertyName(“referrer”)]
public string Referrer { get; set; }

[JsonPropertyName(“violated-directive”)]
public string ViolatedDirective { get; set; }

[JsonPropertyName(“effective-directive”)]
public string EffectiveDirective { get; set; }

[JsonPropertyName(“original-policy”)]
public string OriginalPolicy { get; set; }

[JsonPropertyName(“blocked-uri”)]
public string BlockedUri { get; set; }

[JsonPropertyName(“status-code”)]
public int StatusCode { get; set; }
}

And you can modify the middleware like this.

app.Use(async (context, next) =>
{
context.Response.Headers.Add(“Content-Security-Policy-Report-Only”,
“default-src ‘self’; report-uri /cspreport”);
await next();
});

Since the Post method in using another content type – application/csp-report you might get 415 error – to fix this you need to configure this content type in ASP.NET Core MVC, like this.

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddMvcOptions(options =>
{
options.InputFormatters.OfType<SystemTextJsonInputFormatter>().First().SupportedMediaTypes.Add(
new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(“application/csp-report”)
);
});
}

Now you can run the application and you will be able to see the CSP violations in logger. There are some nuget packages already available to configure the CSP in ASP.NET Core apps. It is recommended to enable CSP in web apps.

Happy Programming 🙂

Build client web assets for your Razor Class Library

Razor Class Libraries are .NET class libraries setup with the Razor SDK to enable building Razor files (.razor, cshtml) and to include client web assets (.js, .css, images, etc.). Client web assets often need to be built or processed using tools like npm and webpack. But integrating a client web asset build pipeline into the build process of a Razor Class Library can be challenging. It’s error prone and sometimes results in fragile solutions, like relying on the ordering of tasks in the build process that can change between releases.

In this post we’ll show you how to integrate npm and webpack into the build process for your Razor Class Library. For folks who want a solution that just works, we’ll look at the new experimental Microsoft.AspNetCore.ClientAssets package that handles this integration for you automatically provided you have the right tools installed. We’ll also walk through all the details of how to set this up using MSBuild for folks that want to be able to control and customize the process. While the focus of this post is npm and webpack, the solution that we provide here can easily be adapted to other tools like yarn, rollup, etc.

Adding a client web assets build process

There are two things that we want to happen as part of the build process to integrate handling of client web assets:

Restore client web assets managed by other package managers (npm, yarn).
Build/generate client web assets and include the results as part of the build output as static web assets.

In our examples, we’ll put all the client web asset sources into an assets folder within the root of the project.

For the output of the build process we have a couple of options:

Put the outputs in the dist subfolder. This is common in many tools and makes it easy to glance at the output. However, if you’re using Git (or some other version control system), you may be forced to add an entry into the .gitignore file to avoid accidentally adding the outputs to source control, and it makes cleaning the workspace harder.
Put the outputs in the obj folder. This is more inline with how builds work in .NET and doesn’t require any additional setup. We’ll use this approach.

Ideally, we want these steps to be incremental, meaning that they only run when any of the inputs have changed and don’t run when everything is up to date. For example, we only want to run npm install when the packages are not available locally or when the package.json file has been updated.

Using the MicrosoftAspNetCore.ClientAssets package

All of this build logic can be included in a NuGet package and reused across multiple projects. In fact, that’s what we’ve done in the experimental Microsoft.AspNetCore.ClientAssets package, which will automatically add support for integrating npm, webpack, or other tools to your build pipeline.

To use the MicrosoftAspNetCore.ClientAssets package:

Add a package reference to Microsoft.AspNetCore.ClientAssets from your project.
Add an assets folder with a package.json file.
In assets/package.json specify your dependencies and defines the build:Debug and build:Release scripts you want to run for Debug and Release builds.

That’s it! You’re read to restore and build your client web assets. You can find a sample that shows using this package to build TypeScript files in a Razor Class Library here.

We think this package will fit the needs of most users, but give it a try and let us know what you think by submitting any issues you find on GitHub. If for some reason this doesn’t work for a tool you’re using, you can add the MSBuild logic directly to your project and update and adapt it to fit your needs. We’ll cover that next.

Add a client web assets build process using MSBuild

The MicrosoftAspNetCore.ClientAssets package provides custom MSBuild targets to add a client web assets build process to your project. In this section, we’ll look at how these targets work, so that you can customize them.

Integrating npm install with Razor Class Libraries

To restore client web assets from npm, we’ll create a task to invoke npm install. MSBuild tasks allow you to specify Inputs and Outputs, which are used to determine if the target needs to run by examining whether an input is newer than one of the outputs. Since we’re putting all our client sources in the assets folder, we can use the assetspackage.json file as an input to determine if we need to run the npm install command or not. When npm install is run, a node_modules.package-lock.json file is created, which we can use for the output. If package.json is changed, it will be newer than node_modules.package-lock.json, which will trigger a new install the next time the build is triggered.

The complete target is displayed below:

<Target Name=”NpmInstall” Inputs=”assetspackage.json” Outputs=”assetsnode_modules.package-lock.json”>
<Message Importance=”high” Text=”Running npm install…” />
<Exec Command=”npm install” WorkingDirectory=”assets” />
</Target>

Running an npm command and collecting the outputs as static web assets

Next we’ll create a target that runs an npm command and collects the outputs as static web assets. In our example, we’ll create an NpmRunBuild target that runs the build:$(Configuration) script in package.json with every build (where $(Configuration) is Release or Debug).

The NpmRunBuild target will do the following:

Run the given npm command.
Collect the outputs from the command.
Add the outputs as Content items, and link them to where they would be in the wwwroot folder.
Write a file to disk with the list of generated files to use as an output for incrementalism.

We’ll start by defining the NpmRunBuild target so that it runs after NpmInstall but before AssignTargetPaths. The target executes the specified npm command, and the command output is directed to $(IntermediateOutputPath)npm, which normally points to objDebug|Releasenet6.0.

<Target Name=”NpmRunBuild” DependsOnTargets=”NpmInstall” BeforeTargets=”AssignTargetPaths”>
<Exec Command=”npm run build:$(Configuration) — -o $(IntermediateOutputPath)npm” WorkingDirectory=”assets” />
</Target>

Next we’ll add the build outputs as Content items and link them to the wwwroot folder. We can do so by declaring three item groups after invoking the Exec task as follows:

<ItemGroup>
<_NpmOutput Include=”$(IntermediateOutputPath)npm**” />
<Content Include=”@(_NpmOutput)” Link=”wwwroot%(_NpmOutput.RecursiveDir)%(_NpmOutput.FileName)%(_NpmOutput.Extension)” />
<FileWrites Include=”@(_NpmOutput)” />
</ItemGroup>

The _NpmOutput item group captures all the files in the output content. We then include these items as Content and link them to the wwwroot folder. Finally, we add these items to the list of FileWrites so they can be cleaned up property.

The last step is to make this target run only when the sources are changed. To do so, we need to declare Inputs and Outputs on the target in the same way we did for the NpmInstall target. MSBuild will check the outputs, and execute the target in two situations:

The outputs don’t exist.
Any outputs are older than any of the inputs.

Given that we don’t know what the outputs of running the npm command are going to be, we’ll generate a file with the list of output files. The output file listing will always have a well-known file name (npmbuild.complete.txt), so we’ll be able to use it as the output for our target. We can produce the output file listing like this:

<WriteLinesToFile File=”$(IntermediateOutputPath)npmbuild.complete.txt” Lines=”@(_NpmOutput)” />

Since we’re generating a file, we also need to add it to the list of FileWrites as we did with the other outputs:

<FileWrites Include=”$(IntermediateOutputPath)npmbuild.complete.txt” />

For the inputs, we can define an item group to capture them as follows:

<ItemGroup>
<NpmBuildInputs Include=”assets**” Exclude=”assetsnode_modules**” />
</ItemGroup>

With all that in place, we can define the inputs and outputs on our NpmRunBuild target as follows:

<ItemGroup>
<NpmBuildInputs Include=”assets**” Exclude=”assetsnode_modules**” />
</ItemGroup>

<Target Name=”NpmRunBuild” DependsOnTargets=”NpmInstall” BeforeTargets=”AssignTargetPaths” Inputs=”@(NpmBuildInputs)” Outputs=”$(IntermediateOutputPath)npmbuild.complete.txt”>
<Exec Command=”$(NpmCommand) — -o $(IntermediateOutputPath)npm” WorkingDirectory=”assets” />

<ItemGroup>
<_NpmOutput Include=”$(IntermediateOutputPath)npm**”></_NpmOutput>
<Content Include=”@(_NpmOutput)” Link=”wwwroot%(_NpmOutput.RecursiveDir)%(_NpmOutput.FileName)%(_NpmOutput.Extension)” />
<FileWrites Include=”@(_NpmOutput)” />
<FileWrites Include=”$(IntermediateOutputPath)npmbuild.complete.txt” />
</ItemGroup>

<WriteLinesToFile File=”$(IntermediateOutputPath)npmbuild.complete.txt” Lines=”@(_NpmOutput)” />
</Target>

This target will only run when you change something in your sources, like your TypeScript files or package.json.

Adding scripts in package.json

With these targets the build pipeline will invoke npm install and npm run build:Debug or npm run build:Release when necessary, passing the output folder as the -o parameter. We need to define these scripts in our package.json to invoke the appropriate tool. To use webpack, the scripts look like this:

“scripts”: {
“build:Debug”: “webpack –mode development”,
“build:Release”: “webpack –mode production”
}

The parameters passed from the Exec task to npm run will transparently flow into the invoked command and override the default output path.

Reusing the MSBuild code

We’ve seen in detail how to put together all the pieces. However, we’ve been very strict in what command to run, where the files should be located, and so on. Next we’ll generalize the solution by using MSBuild to parameterize the process. Here’s how:

<PropertyGroup>
<ClientAssetsDirectory Condition=”‘$(ClientAssetsDirectory)’ == ””>assets</ClientAssetsDirectory>
<ClientAssetsRestoreInputs Condition=”‘$(ClientAssetsRestoreInputs)’ == ””>$(ClientAssetsDirectory)package-lock.json;$(ClientAssetsDirectory)package.json<ClientAssetsRestoreInputs>
<ClientAssetsRestoreOutputs Condition=”‘$(ClientAssetsRestoreOutputs)’ == ””>$(ClientAssetsDirectory)node_modules.package-lock.json<ClientAssetsRestoreOutputs>
<ClientAssetsRestoreCommand Condition=”‘$(ClientAssetsRestoreCommand)’ == ””>npm install<ClientAssetsRestoreCommand>
<ClientAssetsBuildCommand Condition=”‘$(ClientAssetsBuildCommand)’ == ””>npm run build:$(Configuration)<ClientAssetsBuildCommand>
<ClientAssetsBuildOutputParameter Condition=”‘$(ClientAssetsBuildOutputParameter)’ == ””>-o<ClientAssetsBuildOutputParameter>
<ClientAssetsRestoreInputs>$(MSBuildProjectFile);$(ClientAssetsRestoreInputs)</ClientAssetsRestoreInputs>
</PropertyGroup>

<ItemGroup>
<ClientAssetsInputs Include=”$(ClientAssetsDirectory)**” Exclude=”$(DefaultItemExcludes)” />
</ItemGroup>

<Target Name=”NpmInstall” Inputs=”$(ClientAssetsRestoreInputs)” Outputs=”$(ClientAssetsRestoreOutputs)”>
<Message Importance=”high” Text=”Running $(ClientAssetsRestoreCommand)…” />
<Exec Command=”$(ClientAssetsRestoreCommand)” WorkingDirectory=”$(ClientAssetsDirectory)” />
</Target>

<Target Name=”NpmRunBuild” DependsOnTargets=”NpmInstall” BeforeTargets=”AssignTargetPaths” Inputs=”@(ClientAssetsInputs)” Outputs=”$(IntermediateOutputPath)clientassetsbuild.complete.txt”>
<Exec Command=”$(ClientAssetsBuildCommand) — $(ClientAssetsBuildOutputParameter) $(IntermediateOutputPath)clientassets” WorkingDirectory=”$(ClientAssetsDirectory)” />

<ItemGroup>
<_ClientAssetsBuildOutput Include=”$(IntermediateOutputPath)clientassets**”></_ClientAssetsBuildOutput>
<Content Include=”@(_ClientAssetsBuildOutput)” Link=”wwwroot%(_ClientAssetsBuildOutput.RecursiveDir)%(_ClientAssetsBuildOutput.FileName)%(_ClientAssetsBuildOutput.Extension)” />
<FileWrites Include=”@(_ClientAssetsBuildOutput)” />
<FileWrites Include=”$(IntermediateOutputPath)clientassetsbuild.complete.txt” />
</ItemGroup>

<WriteLinesToFile File=”$(IntermediateOutputPath)clientassetsbuild.complete.txt” Lines=”@(_ClientAssetsBuildOutput)” />
</Target>

With the changes we made above, we can adapt the build process by changing the values for the different properties in our project file. For example, we can specify that our client web assets are in the js folder instead of the assets, or change the list of default exclusions:

<PropertyGroup>
<ClientAssetsDirectory>js</ClientAssetsDirectory>
<DefaultItemExcludes>$(ClientAssetsDirectory)dist**</DefaultItemExcludes>
</PropertyGroup>

Summary

Adding a client web assets build process to your .NET projects is now easy using the new experimental Microsoft.AspNetCore.ClientAssets package. Or you can create a custom build process using similar MSBuild logic to fit your needs. We hope you’ll give this functionality a try and let us know what you think on GitHub.

Happy coding!

The post Build client web assets for your Razor Class Library appeared first on .NET Blog.

.NET 6 Launches at .NET Conf, November 9-11

Join the biggest .NET virtual event on the planet and save the date for .NET Conf, November 9-11 on www.dotnetconf.net.

.NET Conf is a FREE, 3 day virtual developer event organized by the .NET community and Microsoft. Next week .NET 6 will launch at .NET Conf 2021! We’re back in the studios this year and we have a lot of fun packed into the three days of learning. Come celebrate and learn about the new release. You won’t want to miss it.

Over the course of these three days, there is a variety of live sessions that feature speakers from the community and .NET teams. We have sessions streaming all day and night between day two and day three of the conference, so everyone can get involved regardless of your time zone. You can join in the fun by interacting with our hosts and asking questions live on Twitter to our speakers. Sponsors are also hosting two virtual attendee parties where you can win prizes by answering .NET trivia questions and solving technical challenges. Best of all, you can take what you learn here and become a better .NET developer.

Join the conversation and ask questions using the hashtag: #dotNETConf on Twitter. You can also subscribe to notifications about .NET Conf and future events.

Conference-at-a-Glance

We will be broadcasting 80+ live sessions with the last 24 hours featuring speakers in their local time zones around the world. We will be syndicating on www.dotnetconf.net, Microsoft Learn TV, .NET YouTube channel and the Visual Studio Twitch channel.

The Keynote will kick off at 8AM Pacific Time on November 9th with Scott Hunter and team showing you all the new things you can do with .NET 6.

Check out the full schedule and speakers here.

Day 1 – November 9
Day one is all about the big news, .NET 6! Join the .NET team on all the new things you can do with the latest release.

8:00 – 9:00
Keynote with Scott Hunter and members of the .NET team

9:00 – 17:00
Sessions from the .NET teams at Microsoft

17:00 – 19:00
Virtual Attendee Party (CodeParty #1). Have fun and win prizes from our sponsors.

Day 2 – November 10
Day two is where we dive deeper into all the things you can do with .NET and our 24 hour broadcast begins with community speakers around the world.

7:00 – 9:00
Virtual Attendee Party (CodeParty #2). Have fun and win prizes from our sponsors.

9:00 – 17:00
Sessions from teams all around Microsoft

17:00 – 23:59
Community sessions in local time zones around the world

Day 3 – November 11
Day three continues our all day and night broadcast with speakers around the world in their own time zones.

0:00 – 17:00
Community sessions in local time zones around the world

 All the times listed are in Pacific Time.

.NET Conf Community Events

We’re also supporting community-run local events to help spread the word about the .NET 6 release. We have partnered with organizers around the globe to bring you community events between November 9, 2021 and January 31, 2022. These events can be in person or virtual depending on local area health and safety guidelines. Join your fellow developers in your local time zone and language to learn even more about .NET 6.

Attend a community event.

Would you like to organize a local event for your community? Take a look at the “Event-in-a-box” on GitHub to help you. Let us know about your event by filling out the Community Event Request Form.

Prizes, Swag, and Fun

20+ sponsors are hosting two virtual attendee parties where you can win prizes by answering .NET trivia questions and solving technical challenges. Tune into the broadcast at the end of day one and beginning of day two to have some fun.

For now, check out some of the free digital swag. Download free wallpapers, themes, 3D printable items, and more. You can also enter to win one of 25 epic swag bags with cool prizes.

We’ll see you there!

 

The post .NET 6 Launches at .NET Conf, November 9-11 appeared first on .NET Blog.