dspencer
dspencer

Reputation: 928

Nuget package to insert project name in web.config

I've created a Nuget package which inserts a key/value pair called ApplicationName in the web.config file with a default value of Application Name.

Is there a way to get the name of the .Net MVC project that a user would be installing the package into the value of the key/value in a human readable format? i.e. Incorrect: ApplicationName Correct: Application Name

If it's not possible to get the project name, I suppose using some sort of command line option could work?

Upvotes: 1

Views: 662

Answers (1)

dspencer
dspencer

Reputation: 928

After a few days of pondering, here is the solution I came up with.

  1. Create a web.config transform file to add the key/value pair to the AppSettings section.
  2. Create an install.ps1 file, that grabs the project name, parses it and injects the new value for AppplicationName in the web.config.

Here's my web.config.install.xdt file:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings xdt:Transform="InsertIfMissing">
    <add key="ApplicationName" value="Application Name" xdt:Transform="InsertIfMissing" xdt:Locator="Match(key)" />
  </appSettings>
</configuration>

Here's is my install.ps1 script:

# Runs every time a package is installed in a project
param($installPath, $toolsPath, $package, $project)

# $installPath is the path to the folder where the package is installed.
# $toolsPath is the path to the tools directory in the folder where the package is installed.
# $package is a reference to the package object.
# $project is a reference to the project the package was installed to.

$p = Get-Project
$project_readable_name = ($p.Name -creplace  '([A-Z\W_]|\d+)(?<![a-z])',' $&').trim()

# Solution based on answer found on Stackoverflow: http://stackoverflow.com/questions/6901954/can-nuget-edit-a-config-file-or-only-add-to-it
$xml = New-Object xml

# Find the web.config 
$config = $project.ProjectItems | where {$_.Name -eq "Web.config"}

if($config) {
    # Find web.config's path on the file system
    $localPath = $config.Properties | where {$_.Name -eq "LocalPath"}

    # Load Web.config as XML
    $xml.Load($localPath.Value)

    # Select the ApplicationName node
    $node = $xml.SelectSingleNode("configuration/appSettings/add[@key='ApplicationName']")

    # Change the ApplicationName value
    $node.SetAttribute("value", $project_readable_name)

    # Save the Web.config file
    $xml.Save($localPath.Value)
}

Hope this helps anyone else!

Upvotes: 2

Related Questions