I have a file which has a variable
$versionNumber = "1.0.0
I need to change the variable value to "$versionNumber = "user_choice"" explicitly.
#------------------------------------------------
# Pack parameters used to create the .nupkg file.
#------------------------------------------------
# Specify the Version Number to use for the NuGet package. If not specified, the version number of the assembly being packed will be used.
# NuGet version number guidance: https://docs.nuget.org/docs/reference/versioning and the Semantic Versioning spec: http://semver.org/
# e.g. "" (use assembly's version), "1.2.3" (stable version), "1.2.3-alpha" (prerelease version).
$versionNumber = "1.0.0"
# Specify any Release Notes for this package.
# These will only be included in the package if you have a .nuspec file for the project in the same directory as the project file.
$releaseNotes = ""
# Specify a specific Configuration and/or Platform to only create a NuGet package when building the project with this Configuration and/or Platform.
# e.g. $configuration = "Release"
# $platform = "AnyCPU"
$configuration = ""
$platform = ""
Any possible approach is advisable.
Use the Get-Content cmdlet to read the file, find the versionNumber variable using a positive lookbehind regex and replace it. Finally, use the Set-Content cmdlet to write it back:
(Get-Content 'youFile.nupkg' -raw) -replace '(?<=\$versionNumber\s=).+', '"user_choice"' |
Set-Content 'youFile.nupkg'
other solution without regex
(get-content "C:\temp\nuckpkg.txt").Replace('$releaseNotes = ""', '$releaseNotes = "user_choice"') |
set-content "C:\temp\nuckpkg.txt"
You haven't properly used the code suggested by Martin .
you are using "$env:Version" which will finally get interpreted to the variable value only... '"' are part of replace syntax.
you should use it in this way "'$env:Version'" .
Regards,
Kvprasoon
Related
I want to collect all the source or header files from a specified folder, also matching a curtain naming convention. I don't want to use GLOBbing, and also couldn't find any examples of an approach using only cmake.
One answer from this question suggests to use ls *.cpp into CMakeLists.txt. So I though of getting a list of sources via invoking a batch script in CMakeLists.
But something is wrong. Though it seems that the output is totally correct, CMake can not find those files. The path is (visually) correct: if I manually type it into add_executable, generating will succeed.
While I still want to know how to achieve the initial intent, I am extremely confused about the reason why totally identical strings compare to false:
CMake log:
-- Manually-typed: C:/Repos/cmake-scanner/src/main.cpp
-- Recieved-batch: C:/Repos/cmake-scanner/src/main.cpp
-- Path strings not identical
CollectSources.bat
#echo off
set arg1=%1
set arg2=%2
powershell -Command "$path = '%1'.Replace('\','/'); $headers = New-Object Collections.Generic.List[string]; ls -Name $path/*.%2 | foreach-object{ $headers.Add($path + '/' + $_)}; $headers"
CMakeLists.txt
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(Auto-scanner)
set(HEADERS)
set(SOURCES)
if(WIN32)
execute_process(
COMMAND CMD /c ${CMAKE_CURRENT_SOURCE_DIR}/CollectSources.bat ${CMAKE_CURRENT_SOURCE_DIR}/include h
OUTPUT_VARIABLE res
)
message(STATUS "Found headers: ${res}")
execute_process(
COMMAND CMD /c ${CMAKE_CURRENT_SOURCE_DIR}/CollectSources.bat ${CMAKE_CURRENT_SOURCE_DIR}/src cpp
OUTPUT_VARIABLE res2
)
message(STATUS "Found sources: ${res2}")
set(${HEADERS} ${res})
endif(WIN32)
message(STATUS "Collected headers: ${HEADERS}")
message(STATUS "Manually-typed: C:/Repos/cmake-scanner/src/main.cpp")
message(STATUS "Recieved-batch: ${res2}")
if(NOT "C:/Repos/cmake-scanner/src/main.cpp" STREQUAL "${res2}")
message(STATUS "Path strings not identical")
else()
message(STATUS "Path strings are identical")
endif()
add_executable(${PROJECT_NAME}
${res}
${res2}
)
target_include_directories(${PROJECT_NAME}
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/src
)
and project tree:
cmake-scanner
|-include
| |-IPublicA.h
| |-IPublicB.h
| |-IPublicC.h
| |-IPublicD.h
|-src
|-main.cpp
https://github.com/ElDesalmado/cmake-scanner.git
UPDATE
Strings' comparison by length yields different results, so I thought maybe there are some trailing characters in the output of execute_process.
So I replaced all the newlines that actually might prevent cmake from finding source files.
string(REGEX REPLACE "\n$" "" ...)
So they compare equal, however still could not be located by cmake.
I had some luck with using OUTPUT_STRIP_TRAILING_WHITESPACE in execute_command and main.cpp has been finally located and project generated. But when there are 2 or more sources this doesn't help.
I m going to try outputting sources' names in a single line and see what would occur...
I have solved the issue.
Cmake accepts lists of sources that must be formatted in a way, that sources' paths are separated with a semicolon.
So the solution was to modifiy batch script to output a string line of semicolon-separated file names. Later I will update the repo and provide the batch code.
In order for CMake to recognize the output from the bathc script as a list of Source/Header files, it must not contain any trailing symbols like whitespaces or newlines and file paths must be separated with a semicolon:
path-to-headerA.h;path-to-headerB.h;path-to-headerC.h;
(It is ok if there is a semiciolon at the end of the string line - CMake accepts that).
Working solution
powershell
#echo off
set arg1=%1
set arg2=%2
powershell -Command "$path = '%1'.Replace('\','/'); $headers = ''; get-childitem $path/*.%2 | select-object -expandProperty Name | foreach-object{ $headers += ($path + '/' + $_ + ';')}; Write-output $headers"
CollectSources.cmake
#Collect source files from a given folder
set(DIR_OF_CollectSources_CMAKE ${CMAKE_CURRENT_LIST_DIR})
function(CollectSources path ext ret)
message(STATUS "Collecting sources *.${ext} from ${path}")
execute_process(
COMMAND CMD /c ${DIR_OF_CollectSources_CMAKE}/CollectSources.bat ${path} ${ext}
OUTPUT_VARIABLE res
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "Sources collected:")
foreach(src ${res})
message(${src})
endforeach()
set(${ret} "${res}" PARENT_SCOPE)
endfunction()
usage in CMakeLists.txt:
include(CollectSources)
CollectSources(${CMAKE_CURRENT_SOURCE_DIR}/include h HEADERS)
Example:
https://github.com/ElDesalmado/cmake-scanner.git
CMake output:
-- Collecting sources *.h from C:/Repos/cmake-scanner/include
-- Sources collected:
C:/Repos/cmake-scanner/include/IPublicA.h
C:/Repos/cmake-scanner/include/IPublicB.h
C:/Repos/cmake-scanner/include/IPublicC.h
C:/Repos/cmake-scanner/include/IPublicD.h
-- Collecting sources *.cpp from C:/Repos/cmake-scanner/src
-- Sources collected:
C:/Repos/cmake-scanner/src/lib.cpp
C:/Repos/cmake-scanner/src/main.cpp
Continuing from this SO question.
When following the openDDS install guide I attempt to run configure from within the command prompt but receive this output recieve this error set:
C:\Users\Supervisor\Desktop\opendds>C:\Users\Supervisor\Desktop\opendds\configure.cmd
Options:
'compiler' => 'gcc'
'verbose' => 1
host system is: win32
compiler is: gcc
Using ace_src: C:/Users/Supervisor/Desktop/opendds/ACE_wrappers
Using tao_src: C:/Users/Supervisor/Desktop/opendds/ACE_wrappers/TAO
ACE_ROOT/ace/config.h exists, skipping configuration of ACE+TAO
ENV: saving current environment
ENV: Appending ;C:\Users\Supervisor\Desktop\opendds\ACE_wrappers\bin;C:\Users\Supervisor\Desktop\opendds\bin;C:\Users\Supervisor\Desktop\opend
ds\ACE_wrappers\lib;C:\Users\Supervisor\Desktop\opendds\lib to PATH
ENV: Setting ACE_ROOT to C:\Users\Supervisor\Desktop\opendds\ACE_wrappers
ENV: Setting MPC_ROOT to C:\Users\Supervisor\Desktop\opendds\ACE_wrappers\MPC
ENV: Setting CIAO_ROOT to unused
ENV: Setting TAO_ROOT to C:\Users\Supervisor\Desktop\opendds\ACE_wrappers\TAO
ENV: Setting DDS_ROOT to C:\Users\Supervisor\Desktop\opendds
ENV: Setting DANCE_ROOT to unused
Use of uninitialized value $mpctype in concatenation (.) or string at configure line 1028.
OpenDDS mwc command line: -type C:\Users\Supervisor\Desktop\opendds\DDS_TAOv2_all.mwc
Use of uninitialized value $mpctype in string eq at configure line 1031.
Running MPC to generate project files.
MPC_ROOT was set to C:\Users\Supervisor\Desktop\opendds\ACE_wrappers\MPC.
Using .../opendds/ACE_wrappers/bin/MakeProjectCreator/config/MPC.cfg
ERROR: Invalid type: C:\Users\Supervisor\Desktop\opendds\DDS_TAOv2_all.mwc
mwc.pl v4.1.8
Usage: mwc.pl [-global <file>] [-include <directory>] [-recurse]
[-ti <dll | lib | dll_exe | lib_exe>:<file>] [-hierarchy]
[-template <file>] [-relative NAME=VAL] [-base <project>]
[-noreldefs] [-notoplevel] [-static] [-genins] [-use_env]
[-value_template <NAME+=VAL | NAME=VAL | NAME-=VAL>]
[-value_project <NAME+=VAL | NAME=VAL | NAME-=VAL>]
[-make_coexistence] [-feature_file <file name>] [-gendot]
[-expand_vars] [-features <feature definitions>]
[-exclude <directories>] [-name_modifier <pattern>]
[-apply_project] [-version] [-into <directory>]
[-gfeature_file <file name>] [-nocomments]
[-relative_file <file name>] [-for_eclipse]
[-workers <#>] [-workers_dir <dir> | -workers_port <#>]
[-language <cplusplus | csharp | java | vb>]
[-type <automake | bcb2007 | bcb2009 | bds4 | bmake | cc | cdt6 |
cdt7 | em3 | ghs | gnuace | gnuautobuild | html | make |
nmake | rpmspec | sle | vc6 | vc7 | vc8 | vc10 | vc11 |
vc12 | vc14 | vc71 | vc9 | vxtest | wb26 | wb30 | wix>]
[files]
-base Add <project> as a base project to each generated
project file. Do not provide a file extension, the
.mpb extension will be tried first; if that fails the
.mpc extension will be tried.
-exclude Use this option to exclude directories or files when
searching for input files.
-expand_vars Perform direct expansion, instead of performing relative
replacement with either -use_env or -relative options.
-feature_file Specifies the feature file to read before processing.
The default feature file is default.features under the
config directory.
-features Specifies the feature list to set before processing.
-for_eclipse Generate files for use with eclipse. This is only
useful for make based project types.
-gendot Generate .dot files for use with Graphviz.
-genins Generate .ins files for use with prj_install.pl.
-gfeature_file Specifies the global feature file. The
default value is global.features under the
config directory.
-global Specifies the global input file. Values stored
within this file are applied to all projects.
-hierarchy Generate a workspace in a hierarchical fashion.
-include Specifies a directory to search when looking for base
projects, template input files and templates. This
option can be used multiple times to add directories.
-into Place all output files in a mirrored directory
structure starting at <directory>. This should be a
full path. If any project within the workspace is
referenced via a full path, use of this option is
likely to cause problems.
-language Specify the language preference; possible values are
[cplusplus, csharp, java, vb]. The default is
cplusplus.
-make_coexistence If multiple 'make' based project types are
generated, they will be named such that they can coexist.
-name_modifier Modify output names. The pattern passed to this
parameter will have the '*' portion replaced with the
actual output name. Ex. *_Static
-apply_project When used in conjunction with -name_modifier, it applies
the name modifier to the project name also.
-nocomments Do not place comments in the generated files.
-noreldefs Do not try to generate default relative definitions.
-notoplevel Do not generate the top level target file. Files
are still processed, but no top level file is created.
-recurse Recurse from the current directory and generate from
all found input files.
-relative Any $() variable in an mpc file that is matched to NAME
is replaced by VAL only if VAL can be made into a
relative path based on the current working directory.
This option can be used multiple times to add multiple
variables.
-relative_file Specifies the relative file to read before processing.
The default relative file is default.rel under the
config directory.
-static Specifies that only static projects will be generated.
By default, only dynamic projects are generated.
-template Specifies the template name (with no extension).
-workers Specifies number of child processes to use to generate
projects.
-workers_dir The directory for storing temporary output files
from the child processes. The default is '/tmp/mpc'
If neither -workers_dir nor -workers_port is used,
-workers_dir is assumed.
-workers_port The port number for the parent listener. If neither
-workers_dir nor -workers_port is used, -workers_dir
is assumed.
-ti Specifies the template input file (with no extension)
for the specific type (ex. -ti dll_exe:vc8exe).
-type Specifies the type of project file to generate. This
option can be used multiple times to generate multiple
types. There is no longer a default.
-use_env Use environment variables for all uses of $() instead
of the relative replacement values.
-value_project This option allows modification of a project variable
assignment. Use += to add VAL to the NAME's value.
Use -= to subtract and = to override the value.
This can be used to introduce new name value pairs to
a project. However, it must be a valid project
assignment.
-value_template This option allows modification of a template input
name value pair. Use += to add VAL to the NAME's
value. Use -= to subtract and = to override the value.
-version Print the MPC version and exit.
Error from MPC, stopped at configure line 1035.
The cmd script being run is:
#echo off
:: Win32 configure script wrapper for OpenDDS
:: Distributed under the OpenDDS License.
:: See: http://www.opendds.org/license.html
for %%x in (perl.exe) do set PERLPATH=%%~dp$PATH:x
if x%PERLPATH%==x (
echo ERROR: perl.exe was not found. This script requires ActiveState Perl.
exit /b 1
)
set PERLPATH=
perl configure -verbose --compiler=gcc %*
if exist setenv.cmd call setenv.cmd
And the section of configure that generates the error is:
my $mwcargs = "-type $mpctype $buildEnv->{'DDS_ROOT'}$slash$ws $static";
$mwcargs .= ' ' . $opts{'mpcopts'} if defined $opts{'mpcopts'};
print "OpenDDS mwc command line: $mwcargs\n" if $opts{'verbose'};
print 'Running MPC to generate ', ($mpctype eq 'gnuace' ? 'makefiles' :
'project files'), ".\n";
if (!$opts{'dry-run'}) {
if (system("perl $ENV{'ACE_ROOT'}/bin/mwc.pl $mwcargs") != 0) {
die "Error from MPC, stopped";
}
}
Where initial unset variable is set:
my $mpctype = ($slash eq '/') ? 'gnuace' : $opts{'compiler_version'};
I have both perl and visual studio installed. Looking up MPC I can find a 'multi-precision library. Could this be because I am using gcc? I have to use GCC in order to create a library to use with the JNI out of this code eventually...
You need to make sure that you are using ActiveState perl on windows, other perl variants seem not to work 100%
From: https://connect.microsoft.com/VisualStudio/Feedback/Details/2264644
According to: https://msdn.microsoft.com/en-us/library/vs/alm/build/scripts/variables
Build.SourceBranch should map to $/teamproject/branch and Build.SourceBranchName should map to "branch" where the full path is $/teamproject/branch
I have a branch structure like $/MyProject/Development/MyBranch and when I try to use these variables in PowerShell (i.e. using BUILD_SOURCEBRANCH and BUILD_SOURCEBRANCHNAME), I am getting:
BUILD_SOURCEBRANCH: $/MyProject
BUILD_SOURCEBRANCHNAME: MyProject
From my understanding of the article, the variables should return $/MyProject/Development/MyBranch and MyBranch respectively.
Anyone else able to repro this behaviour with a TFVC repository? If you set up a vNext build definition with just a PowerShell task and add the following snippet, you'll be able to see the available variables in the output:
[CmdletBinding()]
param()
$environmentVars = get-childitem -path env:*
foreach($var in $environmentVars)
{
$keyname = $var.Key
$keyvalue = $var.Value
Write-Output "${keyname}: $keyvalue"
}
I have to modify the answer as I have new find. After double checking the MSDN article, I found for TFVC BUILD_SOURCEBRANCH will be the root server path for the workspace. So I tried mapping the branch path to Server Path, please refer to the screenshot below. After specifying the Server Path to the branch path, you will get correct value of BUILD_SOURCEBRANCH.
We are building a web-application using the new ASP .NET 5 platform. I am configuring the build and deployment automation tools and I want to have the ability to change the application settings during deployment (like changing the web-service url). In ASP .NET 5 we don't have web.config files anymore, only the new json configuration files. Is there a mechanism in ASP .NET 5 similar to web.config transformation in the previous versions of ASP .NET?
I know that web.configs are not really supported, but they are still used in ASP.Net under IIS.
I had a desire to apply transforms as well as I wanted to control the environment variable from the config like so:
<aspNetCore>
<environmentVariables xdt:Transform="Replace">
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
</environmentVariables>
</aspNetCore>
If you really want to transform them in ASP.Net core / 5 you can use the following method:
Add as many different web.config transform files as you want to your
project. For example, you can add Web.Development.config,
Web.Staging.config, and Web.Production.config, etc... Name them however you like.
Modify your project.json file to output the files by adding this
line to the publishoptions right below your current web.config line:
"web.*.config"
Create a publish profile and modify your powershell script for your
publish profile (located at Web Project\Properties\PublishProperties\profilename-publish.ps1) to add the below modifications:
Add this function above the try catch (I found this function here Web.Config transforms outside of Microsoft MSBuild?, slightly modified.) :
function XmlDocTransform($xml, $xdt)
{
if (!$xml -or !(Test-Path -path $xml -PathType Leaf)) {
throw "File not found. $xml";
}
if (!$xdt -or !(Test-Path -path $xdt -PathType Leaf)) {
throw "File not found. $xdt";
}
"Transforming $xml using $xdt";
$scriptPath = (Get-Variable MyInvocation -Scope 1).Value.InvocationName | split-path -parent
#C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.Tasks.dll
Add-Type -LiteralPath "${Env:ProgramFiles(x86)}\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.XmlTransform.dll"
$xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
$xmldoc.PreserveWhitespace = $true
$xmldoc.Load($xml);
$transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt);
if ($transf.Apply($xmldoc) -eq $false)
{
throw "Transformation failed."
}
$xmldoc.Save($xml);
}
Add these lines ABOVE the Publish-AspNet call:
$xdtFiles = Get-ChildItem $packOutput | Where-Object {$_.Name -match "^web\..*\.config$"};
$webConfig = $packOutput + "web.config";
foreach($xdtFile in $xdtFiles) {
XmlDocTransform -xml $webConfig -xdt "$packOutput$xdtFile"
}
You don't really need config transforms in ASP.NET 5 as it has out of the box support for chained configuration sources. For example, take this sample:
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IApplicationEnvironment appEnv, IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables()
.Build();
}
// ...
}
We add two config sources and building the configuration our of them. if I ask for a config key, it will try to get a value for that key by looking at the sources from last to first order. In the above case, I can work with a config.json file during development and I can ovveride the that by providing the proper configuration from environment variables.
Look at the Configuration docs for more information.
As indicated by #tugberk, you can use environment variables instead which is a much better way of handling this situation. If you are running in a development environment and want to store passwords or connection strings you can also use user secrets to add them. After all that you can also still use environment specific config files like so (This is a ASP.NET 5 Beta 5 Sample):
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(
applicationEnvironment.ApplicationBasePath);
// Add configuration from the config.json file.
configurationBuilder.AddJsonFile("config.json");
// Add configuration from an optional config.development.json, config.staging.json or
// config.production.json file, depending on the environment. These settings override the ones in the
// config.json file.
configurationBuilder.AddJsonFile($"config.{hostingEnvironment.EnvironmentName}.json", optional: true);
if (hostingEnvironment.IsEnvironment(EnvironmentName.Development))
{
// This reads the configuration keys from the secret store. This allows you to store connection strings
// and other sensitive settings on your development environment, so you don't have to check them into
// your source control provider. See http://go.microsoft.com/fwlink/?LinkID=532709 and
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddUserSecrets();
}
// Add configuration specific to the Development, Staging or Production environments. This config can
// be stored on the machine being deployed to or if you are using Azure, in the cloud. These settings
// override the ones in all of the above config files.
// Note: To set environment variables for debugging navigate to:
// Project Properties -> Debug Tab -> Environment Variables
// Note: To get environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]
// Note: To set environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]="[VARIABLE_VALUE]"
// Note: Environment variables use a colon separator e.g. You can override the site title by creating a
// variable named AppSettings:SiteTitle. See
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddEnvironmentVariables();
IConfiguration configuration = configurationBuilder.Build();
We have used wix to create Msi. Each Msi will be having 1 or 2 or 3 features such as Appserver feature, Webserver feature and DB server feature.
Now i was asked to get the list of config files presented in each feature.
It is tough to find the list of web.config files associated with each feature through wxs file.
Is it possible find the list of files associated with a feature with particular search pattern?
For ex. Find all the web.config files packed in Appserver feature.
Is there any way easy way ( querying or some other automated script such as powershell) to get the list?
Wix comes with a .NET SDK referred to as the DTF ("deployment tools foundation"). It wraps the windows msi.dll among other things. You can find these .NET Microsoft.Deployment.*.dll assemblies in the SDK subdirectory of the Wix Toolset installation directory. The documentation is in dtf.chm and dtfapi.chm in the doc subdirectory.
As shown in the documentation, you can use this SDK to write code which queries the msi database with SQL. You will be interested in the Feature, FeatureComponents and File tables.
If you haven't explored the internals of an MSI before, you can open it with orca to get a feel for it.
You can do it by making slight modifications to the Get-MsiProperties function described in this PowerShell article.
Please read the original article and create the prescribed comObject.types.ps1xml file.
function global:Get-MsiFeatures {
PARAM (
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="MSI Database Filename",ValueFromPipeline=$true)]
[Alias("Filename","Path","Database","Msi")]
$msiDbName
)
# A quick check to see if the file exist
if(!(Test-Path $msiDbName)){
throw "Could not find " + $msiDbName
}
# Create an empty hashtable to store properties in
$msiFeatures = #{}
# Creating WI object and load MSI database
$wiObject = New-Object -com WindowsInstaller.Installer
$wiDatabase = $wiObject.InvokeMethod("OpenDatabase", (Resolve-Path $msiDbName).Path, 0)
# Open the Property-view
$view = $wiDatabase.InvokeMethod("OpenView", "SELECT * FROM Feature")
$view.InvokeMethod("Execute")
# Loop thru the table
$r = $view.InvokeMethod("Fetch")
while($r -ne $null) {
# Add property and value to hash table
$msiFeatures[$r.InvokeParamProperty("StringData",1)] = $r.InvokeParamProperty("StringData",2)
# Fetch the next row
$r = $view.InvokeMethod("Fetch")
}
$view.InvokeMethod("Close")
# Return the hash table
return $msiFeatures
}