Nuget PowerShell script to modify Global.asax.cs

后端 未结 4 1883
一生所求
一生所求 2021-01-06 01:22

I\'m building a nuget package for my company MVC4 template. I have run into an issue where I need the Global.asax.cs to be modified to add these two lines:

相关标签:
4条回答
  • 2021-01-06 01:38

    Here's the answer in case someone needs it, this goes in your Install.ps1 inside the Tools folder:

    param($installPath, $toolsPath, $package, $project)
    
    # Read the transformed text from the custom template included in the package
    $customGlobalAsax = $project.ProjectItems | where { $_.Name -eq "Global.asax.cs.custom" }
    $customGlobalAsax.Open()
    $customGlobalAsax.Document.Activate()
    $customGlobalAsax.Document.Selection.SelectAll(); 
    $replacementGlobalAsax = $customGlobalAsax.Document.Selection.Text;
    $customGlobalAsax.Delete()
    
    # Replace the contents of Global.asax.cs
    $globalAsax = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
    if($globalAsax) {
        $globalAsax.Open()
        $globalAsax.Document.Activate()
        $globalAsax.Document.Selection.SelectAll()
        $globalAsax.Document.Selection.Insert($replacementGlobalAsax)
        $globalAsax.Document.Selection.StartOfDocument()
        $globalAsax.Document.Close(0)
    }
    
    0 讨论(0)
  • 2021-01-06 01:41

    In case anyone sees this thread, I want to point out that as of version 2.5 released April, 2013 Nuget will overwrite content files. If using the GUI, the install process will detect the issue and prompt whether or not to overwrite the file. A new option -FileConflictAction allows the setting of a default value.

    See the release notes: http://docs.nuget.org/docs/release-notes/nuget-2.5

    0 讨论(0)
  • 2021-01-06 01:46

    I would take a look at WebActivator before going down the route of writing a PowerShell script to update existing source code. WebActivator is a NuGet package that you can use to add startup and shutdown code into an application without having to modify global.asax.

    You will probably want to use the PostApplicationStartMethod attribute so your bundle registration is done at the end.

    0 讨论(0)
  • 2021-01-06 01:47

    If you want to "replace" some text in some file you can do like this:

    $file = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
    if($file) {
        $file.Open()
        $file.Document.Activate()
        $file.Document.Selection.StartOfDocument()
        $file.Document.ReplaceText("TextToFind`n", "TextToReplace")
    }
    

    Note the `n which is escaping for \n or enter (CR).

    If you need quote character " it can be escaped as `" as well

    0 讨论(0)
提交回复
热议问题