PHPunit execute tests with wrong PDO driver in Symfony 4 - docker

I have a PHP unit working on a remote interpreter perfectly.
It work in all cases without PHP Storm (I.E. using the same command in command line on the docker)
Here is the command command executed by phpstorm, and its the one i try in all situation to compare:
php /var/www/privateapi/vendor/bin/simple-phpunit --bootstrap /var/www/privateapi/tests/bootstrap.php --configuration /var/www/privateapi/phpunit.xml.dist --teamcity --cache-result-file=/va
r/www/privateapi/.phpunit.result.cache
In PhpStorm when I run tests that should communicate with database, it fails because it tries to use a MYSQL driver and I use PGSQL.
Summary:
Working cases:
In commandline, on the docker, with or without DB Tests
In commandline, outside the docker (i.e. docker exec -it ... ), with or without DB Tests
With PHPStorm, with remote interpreter, without DB Tests
Failing case:
With PHPStorm, with remote interpreter, with DB Tests
Here is my conf :
app/config/packages/test/doctrine.yaml
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL_TEST)%'
driver: 'pdo_pgsql'
mapping_types:
container_mode: string
network_provider: string
sensor_status: string
notification_channel: string
server_version: 11
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
app/phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/7.5/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="tests/bootstrap.php"
>
<php>
<ini name="error_reporting" value="-1" />
<server name="SHELL_VERBOSITY" value="-1" />
<server name="SYMFONY_PHPUNIT_REMOVE" value="" />
<server name="SYMFONY_PHPUNIT_VERSION" value="7.5" />
<env name="APP_ENV" value="test" />
<env name="KERNEL_CLASS" value="App\Kernel" />
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
<exclude>
<file>src/Kernel.php</file>
<file>src/Event/Listener/JsonToHtmlDevEventListener.php</file>
</exclude>
</whitelist>
</filter>
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />
</listeners>
</phpunit>
It works well with any code, but as soon as I want to test some use case with Database like this one :
app/tests/Security/Voter/OrganizationVoterTest.php
class OrganizationVoterTest extends KernelTestCase
{
private ?OrganizationVoter $voter;
private ?UserRepository $userRepository;
private ?OrganizationRepository $orgaRepository;
protected function setUp()
{
self::bootKernel();
$container = self::$container;
$this->voter = $container->get(OrganizationVoter::class);
$this->userRepository = $container->get('doctrine')->getRepository(User::class);
$this->orgaRepository = $container->get('doctrine')->getRepository(Organization::class);
parent::setUp();
}
public function testGetMinRequiredLevel()
{
$orga = $this->orgaRepository->findOneBy(['name' => 'orga1']);
[....]
}
}
I will get the following error :
Doctrine\DBAL\Exception\DriverException : An exception occurred in driver: could not find driver
/var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:106
/var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:166
/var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:154
/var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php:28
/var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:362
/var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:1443
/var/www/privateapi/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:890
/var/www/privateapi/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:718
/var/www/privateapi/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:193
/var/www/privateapi/tests/Security/Voter/OrganizationVoterTest.php:32

Thanks to Jakumi, i found out that I needed to manually add the env Var DATABASE_URL_TEST.
Because I am using WSL I should use this as the host docker.for.win.localhost.

Related

Build and run a docker container as a part of integration test in asp.net core

I have integration tests for my asp.net core 3.1 app which runs HostedService. As a part of integrations tests process, I want to build a docker container before tests start. I tried to add following command in test project config :
<Target Name="Test" AfterTargets="Build">
<Exec command="docker run --rm -p 3030:3030 -v $PWD/mocks:/app/mocks dotronglong/faker:stable" />
</Target>
It returned "exited with code 127", so I changed it to be :
<Target Name="Test" AfterTargets="Build">
<Exec command="C:\Program Files\Docker\Docker\resources\bin\docker run --rm -p 3030:3030 -v $PWD/mocks:/app/mocks dotronglong/faker:stable" />
</Target>
And I got "exited with code 9009".
This docker container has a dependency on "mocks" so I have set the project to have :
<ItemGroup>
<None Update="mocks\api.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
Overall, is it a correct way of running a docker container for integration test ? Consider that this test will be run in a CI/CD so the path used for running docker is also important.
You can use Docker.DotNet for create and run a container from a docker image.
For create container:
var address = Environment.OSVersion.Platform == PlatformID.Unix
? new Uri("unix:///var/run/docker.sock")
: new Uri("npipe://./pipe/docker_engine");
var config = new DockerClientConfiguration(address);
var dockerClient = config.CreateClient();
await dockerClient.Containers.CreateContainerAsync(
new CreateContainerParameters
{
Image = "image_name",
Name = "container_name"
});
Then you can start container:
await dockerClient.Containers.StartContainerAsync("container_name", new ContainerStartParameters { });
See here for more information.

HTTPS in docker in Service Fabric for asp.net core not working

I have a asp.net core application hosted in docker . The docker file looks like this
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
LABEL cmbappname="autocomplete"
ARG source
WORKDIR /cmbapp
ADD ${source} .
ENV APP_UTILS=C:\\app
VOLUME ${APP_UTILS}
HEALTHCHECK --retries=5 --interval=100s --start-period=10s CMD curl --fail http://localhost || exit 1
ENTRYPOINT ["dotnet", "MyBus.AutoApi.dll"]
EXPOSE 80
EXPOSE 443
the docker image in hosted in service fabric which has a service manifest like this
<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="AutoApiPkg"
Version="1.0.0"
xmlns="http://schemas.microsoft.com/2011/01/fabric"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ServiceTypes>
<!-- This is the name of your ServiceType.
The UseImplicitHost attribute indicates this is a guest service. -->
<StatelessServiceType ServiceTypeName="AutoApiType" UseImplicitHost="true" />
</ServiceTypes>
<!-- Code package is your service executable. -->
<CodePackage Name="Code" Version="1.0.0">
<EntryPoint>
<!-- Follow this link for more information about deploying Windows containers to Service Fabric: https://aka.ms/sfguestcontainers -->
<ContainerHost>
<ImageName>autoApi</ImageName>
</ContainerHost>
</EntryPoint>
<!-- Pass environment variables to your container: -->
<EnvironmentVariables>
<EnvironmentVariable Name="ASPNETCORE_ENVIRONMENT" Value="Debug" />
<EnvironmentVariable Name="ASPNETCORE_URLS" Value="https://*:443/;http://*:80/;https://*:54100/;http://*:54200/"/>
</EnvironmentVariables>
</CodePackage>
with the container policies in the Applicaiton manifest
<Policies>
<ContainerHostPolicies CodePackageRef="Code" AutoRemove="false" UseDefaultRepositoryCredentials="false" ContainersRetentionCount="2" RunInteractive="true">
<!-- See https://aka.ms/I7z0p9 for how to encrypt your repository password -->
<PortBinding ContainerPort="443" EndpointRef="AutApiTypeEndpoint" />
<PortBinding ContainerPort="80" EndpointRef="LocalAutApiTypeEndpoint" />
<RepositoryCredentials AccountName="[AzureContainerUserName]" Password="[AzureContainerPassword]" PasswordEncrypted="false"/>
<HealthConfig IncludeDockerHealthStatusInSystemHealthReport="true" RestartContainerOnUnhealthyDockerHealthStatus="false" />
</ContainerHostPolicies>
</Policies>
the application runs and is functional without the enviornment variable "ASPNETCORE_URLS"
but when adding the env variable its not functional nor is it reachable.
debugging the container gives the following error logs
Unable to start Kestrel. System.InvalidOperationException: Unable to
configure HTTPS endpoint. No server certificate was specified, and the
default developer certificate could not be fo und or is out of date.
Get a certificate, for example by using Letsencrypt [example], or use a self-signed certificate (for testing).
Use a volume to attach the certificate file to your container.
Use an environment variable to indicate where the certificate is stored:
ASPNETCORE_Kestrel__Certificates__Default__Path=certificate.pfx
Use another environment variable to provide the password to allow access to the private key:
ASPNETCORE_Kestrel__Certificates__Default__Password="****"
More info here.

Tomcat 8.5 context path not working correctly

I have an application with the name cat_tiger.war that gets deployed as localhost:8080/cat_tiger but I want to change the context path to localhost:8080/cat/lion/ instead. I've added the META-INF/context.xml file as
<?xml version="1.0" encoding="UTF-8"?>
<Context copyXML="true" docBase="cat_tiger" path="/cat/lion"/>
and the server.xml file to be
<Host name="localhost" appBase="webapps"
copyXML="true" deployXML="true"
unpackWARs="true" autoDeploy="true">
but it still deploys as localhost:8080/cat_tiger/
Any ideas as to what else needs to be changed?
EDIT:
[1] Tomcat 8.5.3
[2]
04-Sep-2018 13:50:41.830 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDescriptor Deployment of configuration descriptor [/opt/tomcat/conf/Catalina/localhost/cat_tiger.xml] has finished in [2,750] ms
...
...
04-Sep-2018 13:50:39.070 WARNING [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDescriptor A docBase [/opt/tomcat/webapps/cat_tiger] inside the host appBase has been specified, and will be ignored
[3] I'm deploying through Netbeans but will have to be deployed in a Docker container eventually.
I don't understand why you are having problems, but I've created the web project using NetBeans 8.2 (File > New Project... > Java Web > Web Application), and successfully changed the context, so perhaps if I give details of my project you can identify where there's a crucial difference.
1 cat_tiger\web\META-INF\context.xml
My file looks identical to yours:
<?xml version="1.0" encoding="UTF-8"?>
<Context copyXML="true" docBase="cat_tiger" path="/cat/lion"/>
[2] Run output
Select the project node, right click and select Run from the popup menu to run on Tomcat 8.5:
ant -f D:\\NB82\\cat_tiger -Dnb.internal.action.name=run -Ddirectory.deployment.supported=true -DforceRedeploy=false -Dnb.wait.for.caches=true -Dbrowser.context=D:\\NB82\\cat_tiger -Duser.properties.file=C:\\Users\\johndoe\\AppData\\Roaming\\NetBeans\\8.2\\build.properties run
init:
deps-module-jar:
deps-ear-jar:
deps-jar:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
In-place deployment at D:\NB82\cat_tiger\build\web
Deployment is in progress...
deploy?config=file%3A%2FC%3A%2FUsers%2Fjohndoe%2FAppData%2FLocal%2FTemp%2Fcontext7953615149857268018.xml&path=/cat/lion
OK - Deployed application at context path [/cat/lion]
Start is in progress...
start?path=/cat/lion
OK - Started application at context path [/cat/lion]
run-deploy:
Browsing: http://localhost:8080/cat/lion
run-display-browser:
run:
BUILD SUCCESSFUL (total time: 0 seconds)
Actually, you probably don't need to run the application to see the problem; just select Deploy instead of Run from the popup menu. This is the output I get from Deploy:
ant -f D:\\NB82\\cat_tiger -Dnb.internal.action.name=redeploy -Ddirectory.deployment.supported=true -DforceRedeploy=true -Dnb.wait.for.caches=true -Dbrowser.context=D:\\NB82\\cat_tiger -Duser.properties.file=C:\\Users\\johndoe\\AppData\\Roaming\\NetBeans\\8.2\\build.properties run-deploy
init:
deps-module-jar:
deps-ear-jar:
deps-jar:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
Undeploying ...
undeploy?path=/cat_tiger
OK - Undeployed application at context path [/cat_tiger]
In-place deployment at D:\NB82\cat_tiger\build\web
Deployment is in progress...
deploy?config=file%3A%2FC%3A%2FUsers%2Fjohndoe%2FAppData%2FLocal%2FTemp%2Fcontext5063723197082921373.xml&path=/cat/lion
OK - Deployed application at context path [/cat/lion]
Start is in progress...
start?path=/cat/lion
OK - Started application at context path [/cat/lion]
run-deploy:
BUILD SUCCESSFUL (total time: 0 seconds)
[3] Tomcat log
Here are the deployment details in the Tomcat log, where you can see that my deployment shows the context correctly, whereas yours does not:
05-Sep-2018 23:09:09.321 INFO [http-nio-8080-exec-6] org.apache.catalina.startup.HostConfig.deployDescriptor Deploying configuration descriptor [C:\apache-tomcat-8.5.20\conf\Catalina\localhost\cat#lion.xml]
05-Sep-2018 23:09:09.334 INFO [http-nio-8080-exec-6] org.apache.catalina.startup.HostConfig.deployDescriptor Deployment of configuration descriptor [C:\apache-tomcat-8.5.20\conf\Catalina\localhost\cat#lion.xml] has finished in [13] ms
05-Sep-2018 23:09:09.338 INFO [http-nio-8080-exec-5] org.apache.catalina.util.LifecycleBase.start The start() method was called on component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/cat/lion]] after start() had already been called. The second call will be ignored.
[4] C:\apache-tomcat-8.5.20\conf\Catalina\localhost\cat#lion.xml
This is the file Tomcat created when deploying the application:
<?xml version="1.0" encoding="UTF-8"?>
<Context copyXML="true" docBase="D:\NB82\cat_tiger\build\web" path="/cat/lion"/>
Note that docBase contains an absolute path.
[5] server.xml
Here's the entire content. I'm using Tomcat 8.5. Note that the <host> element is slightly different to yours, but when I added copyXML="true" deployXML="true" to the <host> element (so it looked like yours) everything continued to work fine:
<?xml version="1.0" encoding="UTF-8"?>
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<GlobalNamingResources>
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<Service name="Catalina">
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" relaxedQueryChars="[]|{}^+\`"<>"/>
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>
<Engine defaultHost="localhost" name="Catalina">
<Realm className="org.apache.catalina.realm.LockOutRealm">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log" suffix=".txt"/>
<Context docBase="C:\apache-tomcat-8.5.20\wtpwebapps\PlusServlet" path="/PlusServlet" reloadable="true" source="org.eclipse.jst.jee.server:PlusServlet"/>
</Host>
</Engine>
</Service>
</Server>
Updated 9/6/2018:
Ignore the answer given above! Even though it happened to work for my configuration, the approach is explicitly disallowed in the Tomcat documentation.
Specifically, path should not be specified within the <Context> of a context.xml file placed within the application's META-INF directory. From the path description in the Common Attributes section of the Tomcat 8.5 documentation for the Context Container:
This attribute must only be used when statically defining a Context in
server.xml. In all other circumstances, the path will be inferred from
the filenames used for either the .xml context file or the docBase.
Even when statically defining a Context in server.xml, this attribute
must not be set unless either the docBase is not located under the
Host's appBase or both deployOnStartup and autoDeploy are false. If
this rule is not followed, double deployment is likely to result.

ivy:listmodule does not find an existing module

We have our shared Ivy repository on an nginx web server reachable within our intranet.
I configured a url resolver to read from the shared repository and an ssh resolver to write to it, mostly following Jason Grimes' excellent blog post on managing dependencies in non-Java projects.
Now I just successfully published a module to the repository via the ssh resolver.
In my SFTP client I can see the directory structure and files sitting in the directory served by the web server:
com.organization/modulename/ivy-modulename-2.0.1.xml.md5
com.organization/modulename/ivy-modulename-2.0.1.xml.sha1
com.organization/modulename/ivy-modulename-2.0.1.xml
com.organization/modulename/modulename-2.0.1.zip.md5
com.organization/modulename/modulename-2.0.1.zip.sha1
com.organization/modulename/modulename-2.0.1.zip
However, when I execute ivy:listmodule it doesn't seem to find it. Frankly, it doesn't output anything apart from the ivysettings initialization output.
This is the Ant target I am executing:
<!-- ================================
target: check-already-in-repo
Check if the current version of a module already exists in the (shared) repository.
================================ -->
<target name="check-already-in-repo">
<ivy:listmodules resolver="shared" organisation="${ivy.organisation}" module="${ivy.module}" revision="${version}" property="already-in-repo" value="true"/>
<ac:if>
<isset property="already-in-repo"/>
<then>
<echo>${ivy.module} ${version} already exists in the repository.</echo>
<echo>Skipping publishing of ${ivy.module}.</echo>
</then>
</ac:if>
</target>
And this is the only output:
$ ant check-already-in-repo -Dversion=2.0.1 -Divy.organisation=com.organization -Divy.module=modulename
Buildfile: [...]/build.xml
check-already-in-repo:
[ivy:listmodules] :: Apache Ivy 2.4.0-rc1 - 20140315220245 :: http://ant.apache.org/ivy/ ::
[ivy:listmodules] :: loading settings :: file = [...]/build/ivysettings.xml
BUILD SUCCESSFUL
Total time: 0 seconds
I checked the value of ivy.shared.default.root and the corresponding ivy and artifact patterns and they're all matching (I kept them simple).
I tried it with the glob matcher and called ivy:listmodules with organization=*, module=* and revision=*, so it should in every case return something. Which it doesn't.
What do I miss?
Here's the rest of the relevant config:
<ivysettings>
<!-- This file is referenced from multiple projects - DO NOT EDIT! -->
<!-- shared -->
<property name="ivy.shared.default.root" value="http://10.79.1.30/ivy"/>
<property name="ivy.shared.default.ivy.pattern" value="[organisation]/[module]/ivy-[module]-[revision].[ext]"/>
<property name="ivy.shared.default.artifact.pattern" value="[organisation]/[module]/[artifact]-[revision].[ext]"/>
<!-- local -->
<property name="ivy.local.default.root" value="${ivy.default.ivy.user.dir}/local"/>
<property name="ivy.local.default.ivy.pattern" value="${ivy.shared.default.ivy.pattern}"/>
<property name="ivy.local.default.artifact.pattern" value="${ivy.shared.default.artifact.pattern}"/>
<settings defaultResolver="default"/>
<resolvers>
<filesystem name="local">
<ivy pattern="${ivy.local.default.root}/${ivy.local.default.ivy.pattern}" />
<artifact pattern="${ivy.local.default.root}/${ivy.local.default.artifact.pattern}" />
</filesystem>
<!-- read access -->
<url name="shared">
<ivy pattern="${ivy.shared.default.root}/${ivy.shared.default.ivy.pattern}" />
<artifact pattern="${ivy.shared.default.root}/${ivy.shared.default.artifact.pattern}" />
</url>
<!-- write access -->
<ssh name="ssh" host="10.79.1.30" port="22" user="ivy" userPassword="${ivy.ssh.password}" publishPermissions="0664">
<ivy pattern="${ivy.shared.default.ivy.pattern}" />
<artifact pattern="${ivy.shared.default.artifact.pattern}" />
</ssh>
<chain name="default" returnFirst="true">
<resolver ref="local"/>
<resolver ref="shared"/>
</chain>
</resolvers>
</ivysettings>
After executing the Ant target with the -d (debug) option something caught my eye:
$ ant check-already-in-repo -Dversion=2.0.1 -Divy.organisation=com.organization -Divy.module=modulename -d
[...]
[ivy:listmodules] using shared to list all in http://10.79.1.30/ivy/
[ivy:listmodules] HTTP response status: 403 url=http://10.79.1.30/ivy/
[ivy:listmodules] CLIENT ERROR: Forbidden url=http://10.79.1.30/ivy/
[ivy:listmodules] HTTP response status: 403 url=http://10.79.1.30/ivy/
[ivy:listmodules] CLIENT ERROR: Forbidden url=http://10.79.1.30/ivy/
[ivy:listmodules] problem while listing resources in http://10.79.1.30/ivy/ with shared (java.io.IOException: The HTTP response code for http://10.79.1.30/ivy/ did not indicate a success. See log for more detail.)
[ivy:listmodules] java.io.IOException: The HTTP response code for http://10.79.1.30/ivy/ did not indicate a success. See log for more detail.
[...]
It seems for listmodules to work, the web server needs to have directory listings enabled. And indeed, after adding
location /ivy {
autoindex on;
}
to the nginx config and restarting the web server it finally worked as expected!
$ ant check-already-in-repo -Dversion=2.0.1 -Divy.organisation=com.organization -Divy.module=modulename
Buildfile: [...]/build.xml
check-already-in-repo:
[ivy:listmodules] :: Apache Ivy 2.4.0-rc1 - 20140315220245 :: http://ant.apache.org/ivy/ ::
[ivy:listmodules] :: loading settings :: file = [...]/build/ivysettings.xml
[echo] modulename 2.0.1 already exists in the repository.
[echo] Skipping publishing of modulename.
BUILD SUCCESSFUL
Total time: 0 seconds
Hooray! :-)

Nuget PowerShell script to modify Global.asax.cs

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:
using System.Web.Optimization;
at the top, before the namespace and
BundleConfig.RegisterBundles(BundleTable.Bundles);
at the end of the Application_Start() method
I tried creating a Global.asax.cs.pp with namespace $rootnamespace$ inside it, but that doesn't seem to work. It seems Nuget wont overwrite existing files?
My last option, as I see it, is to write a powershell script (Install.ps1?) to do this. Here's my template.nuspec
<?xml version="1.0" encoding="utf-8"?>
<package>
<metadata>
<id>Template.MVC4</id>
<version>1.5</version>
<title>MVC4 Template</title>
<description>Installs and configures files for MVC 4 application template.</description>
<authors>Me</authors>
<language>en-US</language>
<dependencies>
<dependency id="Microsoft.AspNet.Web.Optimization" />
</dependencies>
<iconUrl>http://www.someurl.com/Logo.jpg</iconUrl>
</metadata>
<files>
<file src="Template\Helpers\*" target="content\Helpers\" />
<file src="Template\Content\*.css" target="content\Content\" />
<file src="Template\Content\animGif\*" target="content\Content\animGif\" />
<file src="Template\Content\custom-theme\*" target="content\Content\custom-theme\" />
<file src="Template\Content\templateImages\*" target="content\Content\templateImages\" />
<file src="Template\Scripts\*" target="content\Scripts\" />
<file src="Template\Views\Shared\*" target="content\Views\Shared\" />
<file src="Template\Views\Home\*" target="content\Views\Home\" />
<file src="Template\Views\_ViewStart.cshtml" target="content\Views\" />
<file src="NuGetPackage\App_Start\*" target="content\App_Start\" />
<file src="NuGetPackage\Controllers\*" target="content\Controllers\" />
<file src="NuGetPackage\Helpers\*" target="content\Helpers\" />
<file src="NuGetPackage\Models\*" target="content\Models\" />
<file src="NuGetPackage\Views\*" target="content\Views\" />
<file src="NuGetPackage\*" target="content\" />
</files>
</package>
My question is 2 fold, 1) am I doing something wrong in my .nuspec? and 2) if modifying a Global.asax with .pp isn't an option, then what is the powershell script that I'd need to write to have this run automatically when this nuget is added to a project, and do I need to do anything special for it to run (reading the docs seems like just placing Install.ps1 in tools\ will do)?
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)
}
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.
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
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

Resources