Tuesday, November 20, 2018

Keeping Secrets out of the web.config

See here for Microsofts official recommendations on best practices to keep secrets out of the web config.

I am mostly concerned about appSettings and connectionStrings sections in the web.config

The Microsoft article says everything I am going to say below, but they are some important points to consider.

appSettings

To keep your appSettings secret, put them in another file that is not checked into source control. The contents of this file will be merged with what is in the web.config so this works well to allow developers to override values in appSettings.

The syntax is basically

<appSettings file="..\..\AppSettingsSecrets.config"> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings>

The file attribute accepts paths that are relative or absolve and the file does not have to exist. This is useful when deploying to different environments that may not use this file and instead use VSTS / replacing of tokens to manage values per environment.


connectionStrings

The connectionStrings section isn't as nice as the appSettings. The tags between connectionString tags are replaced by the contents of the external file. The file referenced MUST be in the same directory as the web.config that is referencing it. This means the secret file is per project. The other thing that makes it not work as easily is that it MUST exist otherwise you will get a build error because the project file will try to find the file. You can edit the project file and tell it to only include the file in the project for particular environments, but that is tedious and must be done on each project file.


Thursday, November 8, 2018

Save objects in Visual Studio for reuse later

One easy way to save an object while debugging in Visual Studio so that you can use it later for troubleshooting, or maybe use in LINQPad is to serialize the object to disk.

All the libraries you need are built into .NET and can be done in the Immediate Prompt in Visual Studio.

Save the Object to disk

string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myObject);
System.IO.File.WriteAllText($@"c:\dev\{nameof(myObject)}.json", json);

Read the Object from disk

string json = System.IO.File.ReadAllText(@"c:\dev\myObject.json");
           
var company = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<MyClass>(json);

The caveat to this is that you will need the MyClass available when you bring it back to life.You can also pass Object instead of MyClass if you don't have it.