Get building on VS 2019 machines

This commit is contained in:
Andrew Arnott 2019-10-13 21:48:42 -06:00
Родитель 3d19670578
Коммит 9bf33aeecb
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: A9B9910CDCCDA441
90 изменённых файлов: 1469 добавлений и 351 удалений

Просмотреть файл

@ -1,50 +0,0 @@
version: '{build}'
skip_tags: true
skip_branch_with_pr: true
branches:
only:
- master
- /^v\d+(?:\.\d+)?$/
- /[\b_]validate\b/
skip_commits:
files:
- doc/*
- '**/*.md'
- .vsts-ci.yml
os: Visual Studio 2017
configuration: Release
environment:
VisualStudioVersion: 15.0
GeneratePInvokesTxt: true
TreatWarningsAsErrors: true
install:
- choco install pandoc
before_build:
- ps: >-
.\build.ps1 -Restore
#$blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
build_script:
- ps: .\build.ps1 -Build
test_script:
- ps: .\build.ps1 -Test -NoParallelTests
after_build:
- ps: Get-ChildItem bin\*.pinvokes.txt -rec |? { $_.directory -notmatch 'tests' } |% { Push-AppveyorArtifact $_ -DeploymentName "PInvoke method coverage" }
- ps: Get-ChildItem bin\*.exports.txt -rec |? { $_.directory -notmatch 'tests' } |% { Push-AppveyorArtifact $_ -DeploymentName "Exported methods" }
- ps: Get-ChildItem bin\*.nupkg -rec |% { Push-AppveyorArtifact $_ -DeploymentName "NuGet Package" }
- ps: >-
$reportdir = "bin\$env:configuration"
tools\Get-CoverageReport.ps1 -NoBuild -Configuration $env:configuration -OutFile "$reportdir\coverage.md"
pandoc -f markdown -t html "$reportdir\coverage.md" -o "$reportdir\coverage.html"
Push-AppveyorArtifact "$reportdir\coverage.html" -DeploymentName "PInvoke coverage report"
Push-AppveyorArtifact "$reportdir\coverage.md" -DeploymentName "PInvoke coverage report"
notifications:
- provider: Webhook
url: https://webhooks.gitter.im/e/c4d61fc5002e9a62a22f
on_build_success: true
on_build_failure: true
on_build_status_changed: true

157
.editorconfig Normal file
Просмотреть файл

@ -0,0 +1,157 @@
# EditorConfig is awesome:http://EditorConfig.org
# top-most EditorConfig file
root = true
# Don't use tabs for indentation.
[*]
indent_style = space
# (Please don't specify an indent_size here; that has too many unintended consequences.)
# Code files
[*.{cs,csx,vb,vbx,h,cpp,idl}]
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
# Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# JSON files
[*.json]
indent_size = 2
# Dotnet code style settings:
[*.{cs,vb}]
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
dotnet_style_qualification_for_field = true:warning
dotnet_style_qualification_for_property = true:warning
dotnet_style_qualification_for_method = true:warning
dotnet_style_qualification_for_event = true:warning
# Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
# Suggest more modern language features when available
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
# Non-private static fields are PascalCase
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style
dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field
dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected internal, private protected
dotnet_naming_symbols.non_private_static_fields.required_modifiers = static
dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case
# Constants are PascalCase
dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants
dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style
dotnet_naming_symbols.constants.applicable_kinds = field, local
dotnet_naming_symbols.constants.required_modifiers = const
dotnet_naming_style.constant_style.capitalization = pascal_case
# Static fields are camelCase
dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion
dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields
dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style
dotnet_naming_symbols.static_fields.applicable_kinds = field
dotnet_naming_symbols.static_fields.required_modifiers = static
dotnet_naming_style.static_field_style.capitalization = camel_case
# Instance fields are camelCase
dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion
dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields
dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style
dotnet_naming_symbols.instance_fields.applicable_kinds = field
dotnet_naming_style.instance_field_style.capitalization = camel_case
# Locals and parameters are camelCase
dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion
dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters
dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style
dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local
dotnet_naming_style.camel_case_style.capitalization = camel_case
# Local functions are PascalCase
dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions
dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style
dotnet_naming_symbols.local_functions.applicable_kinds = local_function
dotnet_naming_style.local_function_style.capitalization = pascal_case
# By default, name items with PascalCase
dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members
dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style
dotnet_naming_symbols.all_members.applicable_kinds = *
dotnet_naming_style.pascal_case_style.capitalization = pascal_case
# CSharp code style settings:
[*.cs]
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_indent_labels = flush_left
# Prefer "var" everywhere
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = false:suggestion
# Prefer method-like constructs to have a block body
csharp_style_expression_bodied_methods = false:none
csharp_style_expression_bodied_constructors = false:none
csharp_style_expression_bodied_operators = false:none
# Prefer property-like constructs to have an expression-body
csharp_style_expression_bodied_properties = true:none
csharp_style_expression_bodied_indexers = true:none
csharp_style_expression_bodied_accessors = true:none
# Suggest more modern language features when available
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
# Newline settings
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
# Blocks are allowed
csharp_prefer_braces = true:silent

216
.gitignore поставляемый
Просмотреть файл

@ -1,49 +1,74 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
.vs/
# NuGet
/packages/
project.lock.json
*.nuget.targets
*.nuget.props
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
build/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
#NUNIT
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
@ -53,6 +78,7 @@ dlldata.c
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
msbuild.binlog
*.wrn
@ -71,14 +97,21 @@ _Chutzpah*
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
@ -91,7 +124,7 @@ _ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding addin-in
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
@ -100,10 +133,18 @@ _TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
*.ncrunch*
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
@ -131,46 +172,179 @@ publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Windows Azure Build Output
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
sql/
*.Cache
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
*.userprefs
*.opendb
*.db
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# dotnet tool local install directory
.store/

16
.vscode/extensions.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,16 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"ms-azure-devops.azure-pipelines",
"ms-vscode.csharp",
"k--kato.docomment",
"editorconfig.editorconfig",
"pflannery.vscode-versionlens",
"davidanson.vscode-markdownlint",
"dotjoshjohnson.xml"
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": []
}

5
.vscode/settings.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,5 @@
{
"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true
}

Просмотреть файл

@ -1,95 +0,0 @@
queue:
name: Hosted VS2017
timeoutInMinutes: 60
trigger:
branches:
include: ["master"]
paths:
exclude: [".github", "doc", "*.md", ".appveyor.yml"]
variables:
BuildConfiguration: Release
VisualStudioVersion: 15.0
GeneratePInvokesTxt: true
TreatWarningsAsErrors: true
ReportDir: bin\$(BuildConfiguration)
steps:
- task: BatchScript@1
inputs:
filename: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsDevCmd.bat
arguments: -no_logo
modifyEnvironment: true
displayName: Setup Environment Variables
- powershell: choco install pandoc
displayName: Install prerequisites
- powershell: .\build.ps1 -Restore
displayName: Restore packages
- powershell: .\build.ps1 -Configuration $(BuildConfiguration) -Build
displayName: Build
- powershell: .\build.ps1 -Configuration $(BuildConfiguration) -Test -NoParallelTests
displayName: Test
- powershell: |
tools\Get-CoverageReport.ps1 -NoBuild -Configuration $(BuildConfiguration) -OutFile "$(ReportDir)\coverage.md"
pandoc -f markdown -t html "$(ReportDir)\coverage.md" -o "$(ReportDir)\coverage.html"
displayName: Collect P/Invoke coverage report
- task: CopyFiles@2
displayName: 'Copy Files to: $(build.artifactstagingdirectory)\PInvoke coverage report'
inputs:
SourceFolder: $(ReportDir)
Contents: |
coverage.html
coverage.md
TargetFolder: $(build.artifactstagingdirectory)\PInvoke coverage report
- task: PublishBuildArtifacts@1
displayName: 'Publish Artifact: PInvoke coverage report'
inputs:
PathtoPublish: $(build.artifactstagingdirectory)\PInvoke coverage report
ArtifactName: PInvoke coverage report
- task: CopyFiles@2
displayName: 'Copy Files to: $(build.artifactstagingdirectory)\PInvoke method coverage'
inputs:
SourceFolder: bin
Contents: '**\*.pinvokes.txt'
TargetFolder: '$(build.artifactstagingdirectory)\PInvoke method coverage'
- task: PublishBuildArtifacts@1
displayName: 'Publish Artifact: PInvoke method coverage'
inputs:
PathtoPublish: $(build.artifactstagingdirectory)\PInvoke method coverage
ArtifactName: PInvoke method coverage
- task: CopyFiles@2
displayName: 'Copy Files to: $(build.artifactstagingdirectory)\Exported methods'
inputs:
SourceFolder: bin
Contents: '**\*.exports.txt'
TargetFolder: '$(build.artifactstagingdirectory)\Exported methods'
- task: PublishBuildArtifacts@1
displayName: 'Publish Artifact: Exported methods'
inputs:
PathtoPublish: $(build.artifactstagingdirectory)\Exported methods
ArtifactName: Exported methods
- task: CopyFiles@2
displayName: 'Copy Files to: $(build.artifactstagingdirectory)\NuGet packages'
inputs:
SourceFolder: bin
Contents: '**\*.nupkg'
TargetFolder: '$(build.artifactstagingdirectory)\NuGet packages'
- task: PublishBuildArtifacts@1
displayName: 'Publish Artifact: NuGet packages'
inputs:
PathtoPublish: $(build.artifactstagingdirectory)\NuGet packages
ArtifactName: NuGet packages

Просмотреть файл

@ -1,5 +1,4 @@
Contributing
============
# Contributing
There are many thousands of Win32 APIs and this library is not complete.
Please send pull requests to add what you've come up with.
@ -8,11 +7,12 @@ Please send pull requests to add what you've come up with.
### Required
* [Visual Studio 2017](https://www.visualstudio.com/en-us) with the following workloads:
* Desktop development with C++
* .NET desktop development
* .NET Core cross-platform development
* plus the optional component ".NET Core 1.0 - 1.1 development tools for Desktop"
* [Visual Studio 2019](https://www.visualstudio.com) with the workloads/components
specified in the src\.vsconfig file. This is a configuration you can import using the VS installer in order to quickly get the required components installed.
* The version of the .NET Core SDK specified in [global.json](global.json). This will be installed by the `init.ps1` script.
Use the `-InstallLocality Machine` parameter when invoking that script to install the .NET Core SDK at the machine-wide location
so that Visual Studio can reliably find it and load the projects.
* [Windows 8 SDK](https://go.microsoft.com/fwlink/p/?LinkId=226658)
## Guidelines
@ -24,9 +24,7 @@ With the appropriate switch, this script will perform a subset of these function
### Important notices when developing with Visual Studio
Consider using Visual Studio Code or Visual Studio's Open Folder feature instead of opening
the PInvoke.sln in Visual Studio 2017. In exchange for fewer features, you'll have a more responsive UI.
Use Visual Studio 2017 Update 3 (15.3) or later to get several important fixes.
the PInvoke.sln in Visual Studio 2019. In exchange for fewer features, you'll have a more responsive UI.
If you proceed to open the solution in Visual Studio, the following workarounds are necessary:
@ -56,13 +54,6 @@ at the root of the repo, from the Visual Studio Developer Command Prompt:
.\build -Restore
```
#### Consider use of "Lightweight solution load" carefully
Lightweight Solution Load is a new feature in VS 2017 and *may* be used with PInvoke.sln,
but it seems to cause issues with package restore and Intellisense at least in some cases.
![Screenshot of Visual Studio's options page with lightweight solution load highlighted](doc/LightweightSolutionLoadOption.PNG)
#### Workaround Intellisense errors
The C# language service will sometimes reports many errors that are not "real".
@ -328,49 +319,19 @@ When you remove a member of the public API, build error RS0017 occurs.
When you add a member to the public API, build warning RS0016 lets you know you need to
update the PublicAPI.Unshipped.txt file with your new member. This is so that if your
new API is removed later, it can generate an RS0017 error.
Use the analyzer's automatic code fix in Visual Studio 2017 to update the file and
Use the analyzer's automatic code fix in Visual Studio 2019 to update the file and
include that file change in your commit.
### SafeHandles
Safe handles should follow a few rules :
Safe handles should follow a few rules:
* They should have an empty constructor that does nothing. (The marshaller will use this one when it need to create a SafeHandle)
* They should have a constructor allowing to reuse pre-existing handles.
* They should have a static field for each invalid values for easy access.
A good example would be [`SafeHookHandle.cs`](src/User32.Desktop/User32+SafeHookHandle.cs).
## Self-service releases for contributors
As soon as you send a pull request, a build is executed and updated NuGet packages
are published to this Package Feed:
https://ci.appveyor.com/nuget/pinvoke
By adding this URL to your package sources you can immediately install your version
of the NuGet packages to your project. This can be done by adding a nuget.config file
with the following content to the root of your project's repo:
```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="PInvoke CI" value="https://ci.appveyor.com/nuget/pinvoke" />
</packageSources>
</configuration>
```
You can then install the package(s) while you have your new "PInvoke CI" package source selected:
```powershell
Install-Package PInvoke.BCrypt -Pre -Version 0.1.41-beta-g02f355c05d
```
Take care to set the package version such that it exactly matches the AppVeyor build
for your pull request. You can get the version number by reviewing the result of the
validation build for your pull request, clicking ARTIFACTS, and noting the version
of the produced packages.
[SigImp]: http://blogs.msdn.com/b/vbteam/archive/2008/03/14/making-pinvoke-easy.aspx
[APISets]: https://msdn.microsoft.com/en-us/library/windows/desktop/hh802935(v=vs.85).aspx
[APISets8]: https://msdn.microsoft.com/en-us/library/windows/desktop/dn505783(v=vs.85).aspx

Просмотреть файл

@ -1,14 +1,12 @@
P/Invoke
=======
# P/Invoke
[![Build status](https://ci.appveyor.com/api/projects/status/idu56hy4jwytxd3x?branch=master&svg=true)](https://ci.appveyor.com/project/AArnott/pinvoke)
[![Build Status](https://andrewarnott.visualstudio.com/OSS/_apis/build/status/PInvoke)](https://andrewarnott.visualstudio.com/OSS/_build/latest?definitionId=6)
[![Join the chat at https://gitter.im/AArnott/pinvoke](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/AArnott/pinvoke?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Issue Stats][pull-requests-img]][pull-requests-url] [![Issue Stats][issues-closed-img]][issues-closed-url]
A collection of libraries intended to contain all P/Invoke method signatures for popular operating systems.
Think of it as http://pinvoke.net, but proven to compile and work properly, and often
Think of it as https://pinvoke.net, but proven to compile and work properly, and often
with sample usage in the form of unit tests.
Each library is exposed as its own NuGet package, and may include .NET Portable libraries as applicable,
@ -44,6 +42,7 @@ compiler errors if you pass in `null` because both `struct*` and `struct?` overl
To resolve the issue, add a cast to your null: `(struct?)null` to resolve the ambiguity.
### What if I need custom `uint` value not provided in `enum`?
Cast any `uint` to specific `enum` type and pass as parameter.
## Design goals
@ -122,4 +121,4 @@ public release of the library.
[issues-closed-img]: http://www.issuestats.com/github/aarnott/pinvoke/badge/issue
[issues-closed-url]: http://www.issuestats.com/github/aarnott/pinvoke
[PInvokeCoverageReport]: https://ci.appveyor.com/api/projects/aarnott/pinvoke/artifacts/coverage.html?branch=master
[PInvokeCoverageReport]: https://github.com/AArnott/pinvoke/wiki/coverage

23
azure-pipelines.yml Normal file
Просмотреть файл

@ -0,0 +1,23 @@
trigger:
branches:
include:
- master
- 'validate/*'
paths:
exclude:
- doc/
- '*.md'
- .vscode/
variables:
TreatWarningsAsErrors: true
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
BuildConfiguration: Release
BuildPlatform: Any CPU
codecov_token: e300ab17-4cd6-43b5-8292-e824cb320ed3
ci_feed: 6ed146e5-8e9c-46d6-a40f-da9367ed50cd/c20edbb7-8403-4456-8f43-f46b47e360b1
NUGET_PACKAGES: $(Agent.TempDirectory)/.nuget/packages
GeneratePInvokesTxt: true
jobs:
- template: azure-pipelines/build.yml

Просмотреть файл

@ -0,0 +1,37 @@
<#
.SYNOPSIS
Builds all projects in this repo.
.PARAMETER DllPath
The path to the DLL whose PDB is to be converted.
.PARAMETER PdbPath
The path to the PDB to convert. May be omitted if the DLL was compiled on this machine and the PDB is still at its original path.
.PARAMETER OutputPath
The path of the output PDB to write.
#>
#Function Convert-PortableToWindowsPDB() {
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$DllPath,
[Parameter()]
[string]$PdbPath,
[Parameter(Mandatory=$true,Position=1)]
[string]$OutputPath
)
$version = '1.1.0-beta1-64128-01'
$baseDir = "$PSScriptRoot\..\obj\tools"
$pdb2pdbpath = "$baseDir\pdb2pdb.$version\tools\Pdb2Pdb.exe"
if (-not (Test-Path $pdb2pdbpath)) {
if (-not (Test-Path $baseDir)) { New-Item -Type Directory -Path $baseDir | Out-Null }
$baseDir = (Resolve-Path $baseDir).Path # Normalize it
& (& $PSScriptRoot\Get-NuGetTool.ps1) install pdb2pdb -version $version -PackageSaveMode nuspec -OutputDirectory $baseDir -Source https://dotnet.myget.org/F/symreader-converter/api/v3/index.json | Out-Null
}
$args = $DllPath,'/out',$OutputPath,'/nowarn','0021'
if ($PdbPath) {
$args += '/pdb',$PdbPath
}
Write-Verbose "$pdb2pdbpath $args"
& $pdb2pdbpath $args
#}

Просмотреть файл

@ -0,0 +1,22 @@
<#
.SYNOPSIS
Downloads the NuGet.exe tool and returns the path to it.
.PARAMETER NuGetVersion
The version of the NuGet tool to acquire.
#>
Param(
[Parameter()]
[string]$NuGetVersion='5.2.0'
)
$toolsPath = & "$PSScriptRoot\Get-TempToolsPath.ps1"
$binaryToolsPath = Join-Path $toolsPath $NuGetVersion
if (!(Test-Path $binaryToolsPath)) { $null = mkdir $binaryToolsPath }
$nugetPath = Join-Path $binaryToolsPath nuget.exe
if (!(Test-Path $nugetPath)) {
Write-Host "Downloading nuget.exe $NuGetVersion..." -ForegroundColor Yellow
(New-Object System.Net.WebClient).DownloadFile("https://dist.nuget.org/win-x86-commandline/v$NuGetVersion/NuGet.exe", $nugetPath)
}
return (Resolve-Path $nugetPath).Path

Просмотреть файл

@ -0,0 +1,13 @@
if ($env:AGENT_TOOLSDIRECTORY) {
$path = "$env:AGENT_TOOLSDIRECTORY\vs-platform\tools"
} elseif ($env:localappdata) {
$path = "$env:localappdata\vs-platform\tools"
} else {
$path = "$PSScriptRoot\..\obj\tools"
}
if (!(Test-Path $path)) {
New-Item -ItemType Directory -Path $Path | Out-Null
}
(Resolve-Path $path).Path

Просмотреть файл

@ -0,0 +1,28 @@
<#
.SYNOPSIS
Gets the path to the nbgv CLI tool, installing it if necessary.
#>
Param(
)
$existingTool = Get-Command "nbgv" -ErrorAction SilentlyContinue
if ($existingTool) {
return $existingTool.Path
}
if ($env:AGENT_TEMPDIRECTORY) {
$toolInstallDir = "$env:AGENT_TEMPDIRECTORY/$env:BUILD_BUILDID"
} else {
$toolInstallDir = "$PSScriptRoot/../obj/tools"
}
$toolPath = "$toolInstallDir/nbgv"
if (!(Test-Path $toolInstallDir)) { New-Item -Path $toolInstallDir -ItemType Directory | Out-Null }
if (!(Get-Command $toolPath -ErrorAction SilentlyContinue)) {
Write-Host "Installing nbgv to $toolInstallDir"
dotnet tool install --tool-path "$toolInstallDir" nbgv --configfile "$PSScriptRoot/justnugetorg.nuget.config" | Out-Null
}
# Normalize the path on the way out.
return (Get-Command $toolPath).Path

Просмотреть файл

@ -0,0 +1,8 @@
$nuget = & "$PSScriptRoot\Get-NuGetTool.ps1"
$PandocVersion = "2.1.0"
$PandocExePath = "$PSScriptRoot\..\packages\Pandoc.Windows.$PandocVersion\tools\Pandoc\pandoc.exe"
if (!(Test-Path $PandocExePath)) {
& $nuget install Pandoc.Windows -version $PandocVersion -Source https://api.nuget.org/v3/index.json | Out-Null
}
Resolve-Path "$PSScriptRoot\..\packages\Pandoc.Windows.$PandocVersion\tools\Pandoc\pandoc.exe"

Просмотреть файл

@ -0,0 +1,39 @@
<#
.SYNOPSIS
Set environment variables in the environment.
Azure Pipeline and CMD environments are considered.
.PARAMETER Variables
A hashtable of variables to be set.
.OUTPUTS
A boolean indicating whether the environment variables can be expected to propagate to the caller's environment.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
[Parameter(Mandatory=$true, Position=1)]
$Variables
)
if ($Variables.Count -eq 0) {
return $true
}
$cmdInstructions = !$env:TF_BUILD -and $env:PS1UnderCmd -eq '1'
if ($cmdInstructions) {
Write-Warning "Environment variables have been set that will be lost because you're running under cmd.exe"
Write-Host "Environment variables that must be set manually:" -ForegroundColor Blue
}
$Variables.GetEnumerator() |% {
Set-Item -Path env:$($_.Key) -Value $_.Value
# If we're running in Azure Pipelines, set these environment variables
if ($env:TF_BUILD) {
Write-Host "##vso[task.setvariable variable=$($_.Key);]$($_.Value)"
}
if ($cmdInstructions) {
Write-Host "SET $($_.Key)=$($_.Value)"
}
}
return !$cmdInstructions

Просмотреть файл

@ -0,0 +1,40 @@
# This artifact captures all variables defined in the ..\variables folder.
# It "snaps" the values of these variables where we can compute them during the build,
# and otherwise captures the scripts to run later during an Azure Pipelines environment release.
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
$ArtifactBasePath = "$RepoRoot\obj\_artifacts"
$VariablesArtifactPath = "$ArtifactBasePath\variables"
if (-not (Test-Path $VariablesArtifactPath)) { New-Item -ItemType Directory -Path $VariablesArtifactPath | Out-Null }
# Copy variables, either by value if the value is calculable now, or by script
Get-ChildItem -Path "$PSScriptRoot\..\variables" |% {
$value = $null
if (-not $_.BaseName.StartsWith('_')) { # Skip trying to interpret special scripts
# First check the environment variables in case the variable was set in a queued build
if (Test-Path env:$($_.BaseName)) {
$value = Get-Content "env:$($_.BaseName)"
}
# If that didn't give us anything, try executing the script right now from its original position
if (-not $value) {
$value = & $_.FullName
}
if ($value) {
# We got something, so wrap it with quotes so it's treated like a literal value.
$value = "'$value'"
}
}
# If that didn't get us anything, just copy the script itself
if (-not $value) {
$value = Get-Content -Path $_.FullName
}
Set-Content -Path "$VariablesArtifactPath\$($_.Name)" -Value $value
}
@{
"$VariablesArtifactPath" = (Get-ChildItem $VariablesArtifactPath -Recurse);
}

Просмотреть файл

@ -0,0 +1,50 @@
# This script returns all the artifacts that should be collected after a build.
#
# Each powershell artifact is expressed as an object with these properties:
# Source - the full path to the source file
# ArtifactName - the name of the artifact to upload to
# ContainerFolder - the relative path within the artifact in which the file should appear
#
# Each artifact aggregating .ps1 script should return a hashtable:
# Key = path to the directory from which relative paths within the artifact should be calculated
# Value = an array of paths (absolute or relative to the BaseDirectory) to files to include in the artifact.
# FileInfo objects are also allowed.
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
Function EnsureTrailingSlash($path) {
if ($path.length -gt 0 -and !$path.EndsWith('\') -and !$path.EndsWith('/')) {
$path = $path + [IO.Path]::DirectorySeparatorChar
}
$path.Replace('\', [IO.Path]::DirectorySeparatorChar)
}
Get-ChildItem "$PSScriptRoot\*.ps1" -Exclude "_*" -Recurse |% {
$ArtifactName = $_.BaseName
$fileGroups = & $_
if (!$fileGroups -or $fileGroups.Count -eq 0) {
Write-Warning "No files found for the `"$ArtifactName`" artifact."
} else {
$fileGroups.GetEnumerator() | % {
$BaseDirectory = New-Object Uri ((EnsureTrailingSlash $_.Key), [UriKind]::Absolute)
$_.Value | % {
if ($_.GetType() -eq [IO.FileInfo] -or $_.GetType() -eq [IO.DirectoryInfo]) {
$_ = $_.FullName
}
$artifact = New-Object -TypeName PSObject
Add-Member -InputObject $artifact -MemberType NoteProperty -Name ArtifactName -Value $ArtifactName
$SourceFullPath = New-Object Uri ($BaseDirectory, $_)
Add-Member -InputObject $artifact -MemberType NoteProperty -Name Source -Value $SourceFullPath.LocalPath
$RelativePath = [Uri]::UnescapeDataString($BaseDirectory.MakeRelative($SourceFullPath))
Add-Member -InputObject $artifact -MemberType NoteProperty -Name ContainerFolder -Value (Split-Path $RelativePath)
Write-Output $artifact
}
}
}
}

Просмотреть файл

@ -0,0 +1,55 @@
# This script translates all the artifacts described by _all.ps1
# into commands that instruct Azure Pipelines to actually collect those artifacts.
param (
[string]$ArtifactNameSuffix
)
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
if ($env:BUILD_ARTIFACTSTAGINGDIRECTORY) {
$ArtifactStagingFolder = $env:BUILD_ARTIFACTSTAGINGDIRECTORY
} else {
$ArtifactStagingFolder = "$RepoRoot\obj\_artifacts"
if (Test-Path $ArtifactStagingFolder) {
Remove-Item $ArtifactStagingFolder -Recurse -Force
}
}
function Create-SymbolicLink {
param (
$Link,
$Target
)
if ($Link -eq $Target) {
return
}
if (Test-Path $Link) { Remove-Item $Link }
$LinkContainer = Split-Path $Link -Parent
if (!(Test-Path $LinkContainer)) { mkdir $LinkContainer }
Write-Verbose "Linking $Link to $Target"
if ($IsMacOS -or $IsLinux) {
ln $Target $Link
} else {
cmd /c mklink $Link $Target
}
}
# Stage all artifacts
$Artifacts = & "$PSScriptRoot\_all.ps1"
$Artifacts |% {
$DestinationFolder = (Join-Path (Join-Path $ArtifactStagingFolder "$($_.ArtifactName)$ArtifactNameSuffix") $_.ContainerFolder).TrimEnd('\')
$Name = "$(Split-Path $_.Source -Leaf)"
#Write-Host "$($_.Source) -> $($_.ArtifactName)\$($_.ContainerFolder)" -ForegroundColor Yellow
if (-not (Test-Path $DestinationFolder)) { New-Item -ItemType Directory -Path $DestinationFolder | Out-Null }
if (Test-Path -PathType Leaf $_.Source) { # skip folders
Create-SymbolicLink -Link "$DestinationFolder\$Name" -Target $_.Source
}
}
$Artifacts |% { $_.ArtifactName } | Get-Unique |% {
Write-Host "##vso[artifact.upload containerfolder=$_$ArtifactNameSuffix;artifactname=$_$ArtifactNameSuffix;]$ArtifactStagingFolder/$_$ArtifactNameSuffix"
}

Просмотреть файл

@ -0,0 +1,12 @@
if ($env:BUILD_ARTIFACTSTAGINGDIRECTORY) {
$artifactsRoot = $env:BUILD_ARTIFACTSTAGINGDIRECTORY
} else {
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
$artifactsRoot = "$RepoRoot\bin"
}
if (!(Test-Path $artifactsRoot/build_logs)) { return }
@{
"$artifactsRoot/build_logs" = (Get-ChildItem -Recurse "$artifactsRoot/build_logs")
}

Просмотреть файл

@ -0,0 +1,22 @@
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
# Prepare code coverage reports for merging on another machine
if ($env:SYSTEM_DEFAULTWORKINGDIRECTORY) {
Write-Host "Substituting $env:SYSTEM_DEFAULTWORKINGDIRECTORY with `"{reporoot}`""
$reports = Get-ChildItem "$RepoRoot/bin/coverage.cobertura.xml" -Recurse
$reports |% {
$content = Get-Content -Path $_ |% { $_ -Replace [regex]::Escape($env:SYSTEM_DEFAULTWORKINGDIRECTORY), "{reporoot}" }
Set-Content -Path $_ -Value $content -Encoding UTF8
}
} else {
Write-Warning "coverageResults: Azure Pipelines not detected. Machine-neutral token replacement skipped."
}
if (!((Test-Path $RepoRoot\bin) -and (Test-Path $RepoRoot\obj))) { return }
@{
$RepoRoot = (
@(Get-ChildItem "$RepoRoot\bin\coverage.cobertura.xml" -Recurse) +
(Get-ChildItem "$RepoRoot\obj\*.cs" -Recurse)
);
}

Просмотреть файл

@ -0,0 +1,13 @@
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
$BuildConfiguration = $env:BUILDCONFIGURATION
if (!$BuildConfiguration) {
$BuildConfiguration = 'Debug'
}
$PackagesRoot = "$RepoRoot/bin/$BuildConfiguration/Packages"
if (!(Test-Path $PackagesRoot)) { return }
@{
"$PackagesRoot" = (Get-ChildItem $PackagesRoot -Recurse)
}

Просмотреть файл

@ -0,0 +1,15 @@
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
$BuildConfiguration = $env:BUILDCONFIGURATION
if (!$BuildConfiguration) {
$BuildConfiguration = 'Debug'
}
$binRoot = "$RepoRoot\bin\$BuildConfiguration"
tools\Get-CoverageReport.ps1 -NoBuild -Configuration $env:configuration -OutFile "$binRoot\coverage.md"
& (& "$PSScriptRoot\..\Get-pandoc.ps1") -f markdown -t html "$binRoot\coverage.md" -o "$binRoot\coverage.html"
@{
$binRoot = Get-ChildItem "$binRoot\coverage.html","$binRoot\coverage.md";
}

Просмотреть файл

@ -0,0 +1,14 @@
$RepoRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
$BuildConfiguration = $env:BUILDCONFIGURATION
if (!$BuildConfiguration) {
$BuildConfiguration = 'Debug'
}
$binRoot = "$RepoRoot\bin\$BuildConfiguration\net45"
if (Test-Path $binRoot) {
$pinvokes = Get-ChildItem "$binRoot\*.pinvokes.txt","$binRoot\*.exports.txt" -rec |? { $_.directory -notmatch 'tests' }
@{
"$binRoot" = $pinvokes
}
}

Просмотреть файл

@ -0,0 +1,9 @@
$ObjRoot = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..\obj")
if (!(Test-Path $ObjRoot)) { return }
@{
"$ObjRoot" = (
(Get-ChildItem "$ObjRoot\project.assets.json" -Recurse)
);
}

Просмотреть файл

@ -0,0 +1,64 @@
Function Get-SymbolFiles {
[CmdletBinding()]
param (
[parameter(Mandatory=$true)]
[string]$Path
)
$WindowsPdbSubDirName = "symstore"
$ActivityName = "Collecting symbols from $Path"
Write-Progress -Activity $ActivityName -CurrentOperation "Discovery PDB files"
$PDBs = Get-ChildItem -rec "$Path\*.pdb" |? { $_.FullName -notmatch "unittest|tests|\W$WindowsPdbSubDirName\W" }
Write-Progress -Activity $ActivityName -CurrentOperation "De-duplicating symbols"
$PDBsByHash = @{}
$i = 0
$PDBs |% {
Write-Progress -Activity $ActivityName -CurrentOperation "De-duplicating symbols" -PercentComplete (100 * $i / $PDBs.Length)
$hash = Get-FileHash $_
$i++
Add-Member -InputObject $_ -MemberType NoteProperty -Name Hash -Value $hash.Hash
Write-Output $_
} | Sort-Object CreationTime |% {
# De-dupe based on hash. Prefer the first match so we take the first built copy.
if (-not $PDBsByHash.ContainsKey($_.Hash)) {
$PDBsByHash.Add($_.Hash, $_.FullName)
Write-Output $_
}
} |% {
# Collect the DLLs/EXEs as well.
$dllPath = "$($_.Directory)\$($_.BaseName).dll"
$exePath = "$($_.Directory)\$($_.BaseName).exe"
if (Test-Path $dllPath) {
$BinaryImagePath = $dllPath
} elseif (Test-Path $exePath) {
$BinaryImagePath = $exePath
}
Write-Output $BinaryImagePath
# Convert the PDB to legacy Windows PDBs
Write-Host "Converting PDB for $_" -ForegroundColor DarkGray
$WindowsPdbDir = "$($_.Directory.FullName)\$WindowsPdbSubDirName"
if (!(Test-Path $WindowsPdbDir)) { mkdir $WindowsPdbDir | Out-Null }
& "$PSScriptRoot\..\Convert-PDB.ps1" -DllPath $BinaryImagePath -PdbPath $_ -OutputPath "$WindowsPdbDir\$($_.BaseName).pdb"
if ($LASTEXITCODE -ne 0) {
Write-Warning "PDB conversion of `"$_`" failed."
}
Write-Output "$WindowsPdbDir\$($_.BaseName).pdb"
}
}
# This doesn't work off Windows, nor do we need to convert symbols on multiple OS agents
if ($IsMacOS -or $IsLinux) {
return;
}
$BinPath = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..\bin")
if (!(Test-Path $BinPath)) { return }
$symbolfiles = Get-SymbolFiles -Path $BinPath | Get-Unique
@{
"$BinPath" = $SymbolFiles;
}

16
azure-pipelines/build.yml Normal file
Просмотреть файл

@ -0,0 +1,16 @@
parameters:
windowsPool: Hosted Windows 2019 with VS2019
jobs:
- job: Windows
pool: ${{ parameters.windowsPool }}
steps:
- checkout: self
clean: true
- template: install-dependencies.yml
- powershell: '& (./azure-pipelines/Get-nbgv.ps1) cloud -p src'
displayName: Set build number
- template: dotnet.yml
- template: publish-deployables.yml

Просмотреть файл

@ -0,0 +1,34 @@
steps:
- task: VSBuild@1
displayName: Build Visual Studio solution
inputs:
msbuildArgs: /t:build,pack /m /v:m /bl:"$(Build.ArtifactStagingDirectory)/build_logs/msbuild.binlog"
platform: Any CPU
configuration: $(BuildConfiguration)
- powershell: .\build.ps1 -Test
displayName: Test
- task: PowerShell@2
inputs:
filePath: azure-pipelines/variables/_pipelines.ps1
failOnStderr: true
displayName: Update pipeline variables based on build outputs
condition: succeededOrFailed()
- task: PowerShell@2
inputs:
filePath: azure-pipelines/artifacts/_pipelines.ps1
arguments: -ArtifactNameSuffix "-$(Agent.JobName)"
displayName: Publish artifacts
condition: succeededOrFailed()
- task: PublishSymbols@2
inputs:
SymbolsFolder: $(Build.ArtifactStagingDirectory)/symbols-Windows
SearchPattern: '**/*.pdb'
IndexSources: false
SymbolServerType: TeamServices
displayName: Publish symbols to symbol server
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'), eq(variables['Agent.OS'], 'Windows_NT'))

Просмотреть файл

@ -0,0 +1,15 @@
parameters:
initArgs:
steps:
- powershell: |
.\init.ps1 -AccessToken '$(System.AccessToken)' ${{ parameters['initArgs'] }}
dotnet --info
displayName: Install prerequisites
- task: PowerShell@2
inputs:
filePath: azure-pipelines/variables/_pipelines.ps1
failOnStderr: true
displayName: Set pipeline variables based on source

Просмотреть файл

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>

Просмотреть файл

@ -0,0 +1,10 @@
steps:
- task: NuGetCommand@2
displayName: Push packages to CI feed
inputs:
command: push
packagesToPush: bin/$(BuildConfiguration)/Packages/*.nupkg
nuGetFeedType: internal
publishVstsFeed: $(ci_feed)
allowPackageConflicts: true
condition: and(succeeded(), ne(variables['ci_feed'], ''), ne(variables['Build.Reason'], 'PullRequest'))

Просмотреть файл

@ -0,0 +1,2 @@
$globalJson = Get-Content -Path "$PSScriptRoot\..\..\global.json" | ConvertFrom-Json
$globalJson.sdk.version

Просмотреть файл

@ -0,0 +1,11 @@
# This script returns a hashtable of build variables that should be set
# at the start of a build or release definition's execution.
$vars = @{}
Get-ChildItem "$PSScriptRoot\*.ps1" -Exclude "_*" |% {
Write-Host "Computing $($_.BaseName) variable"
$vars[$_.BaseName] = & $_
}
$vars

Просмотреть файл

@ -0,0 +1,15 @@
# This script translates the variables returned by the _all.ps1 script
# into commands that instruct Azure Pipelines to actually set those variables for other pipeline tasks to consume.
# The build or release definition may have set these variables to override
# what the build would do. So only set them if they have not already been set.
(& "$PSScriptRoot\_all.ps1").GetEnumerator() |% {
if (Test-Path -Path "env:$($_.Key.ToUpper())") {
Write-Host "Skipping setting $($_.Key) because variable is already set." -ForegroundColor Cyan
} else {
Write-Host "$($_.Key)=$($_.Value)" -ForegroundColor Yellow
Write-Host "##vso[task.setvariable variable=$($_.Key);]$($_.Value)"
Set-Item -Path "env:$($_.Key)" -Value $_.Value
}
}

Просмотреть файл

@ -24,7 +24,7 @@ Param(
[switch]$Build,
[switch]$Test,
[Parameter()][ValidateSet('debug', 'release')]
[string]$Configuration = $env:configuration,
[string]$Configuration = $env:BUILDCONFIGURATION,
[switch]$WarnAsError = $true,
[switch]$GeneratePInvokesTxt,
[switch]$NoParallelTests
@ -51,13 +51,13 @@ $ToolsFolder = Join-Path $ProjectRoot tools
$BinFolder = Join-Path $ProjectRoot "bin"
$BinConfigFolder = Join-Path $BinFolder $Configuration
$BinTestsFolder = Join-Path $BinConfigFolder "tests"
$PackageRestoreRoot = Join-Path $env:userprofile '.nuget/packages/'
$PackageRestoreRoot = if ($env:NUGET_PACKAGES) { $env:NUGET_PACKAGES } else { Join-Path $env:userprofile '.nuget/packages/' }
# Set script scope for external tool variables.
$MSBuildCommand = Get-Command MSBuild.exe -ErrorAction SilentlyContinue
Function Get-ExternalTools {
if (!$MSBuildCommand) {
if ($Build -and !$MSBuildCommand) {
Write-Error "Unable to find MSBuild.exe. Make sure you're running in a VS Developer Prompt."
exit 1;
}
@ -67,13 +67,14 @@ Get-ExternalTools
if ($Restore -and $PSCmdlet.ShouldProcess($SolutionFile, "Restore packages")) {
Write-Output "Restoring NuGet packages..."
& $MSBuildCommand.Path /t:restore /nologo /m $SolutionFile
& "$PSScriptRoot\init.ps1"
}
if ($Build -and $PSCmdlet.ShouldProcess($SolutionFile, "Build")) {
$buildArgs = @()
$buildArgs += $SolutionFile,'/nologo','/nr:false','/m','/v:minimal','/t:build,pack'
$buildArgs += "/p:Configuration=$Configuration"
$buildArgs += "/clp:ForceNoAlign;Summary"
$buildArgs += '/fl','/flp:verbosity=normal;logfile=msbuild.log','/flp1:warningsonly;logfile=msbuild.wrn;NoSummary;verbosity=minimal','/flp2:errorsonly;logfile=msbuild.err;NoSummary;verbosity=minimal'
if ($GeneratePInvokesTxt) {
$buildArgs += '/p:GeneratePInvokesTxt=true'
@ -109,9 +110,9 @@ if ($Build -and $PSCmdlet.ShouldProcess($SolutionFile, "Build")) {
}
if ($Test -and $PSCmdlet.ShouldProcess('Test assemblies')) {
$TestAssemblies = Get-ChildItem -Recurse "$BinTestsFolder\*.Tests.dll"
$TestAssemblies = Get-ChildItem -Recurse "$BinTestsFolder\*.Tests.dll" |? { $_.Directory -notlike '*netcoreapp*' }
Write-Output "Testing..."
$xunitRunner = Join-Path $PackageRestoreRoot 'xunit.runner.console/2.2.0/tools/xunit.console.x86.exe'
$xunitRunner = Join-Path $PackageRestoreRoot 'xunit.runner.console/2.4.1/tools/net472/xunit.console.x86.exe'
$xunitArgs = @()
$xunitArgs += $TestAssemblies
$xunitArgs += "-html","$BinTestsFolder\testresults.html","-xml","$BinTestsFolder\testresults.xml"

Двоичные данные
doc/LightweightSolutionLoadOption.PNG

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 61 KiB

8
global.json Normal file
Просмотреть файл

@ -0,0 +1,8 @@
{
"sdk": {
"version": "2.2.401"
},
"msbuild-sdks": {
"MSBuild.Sdk.Extras": "2.0.54"
}
}

3
init.cmd Normal file
Просмотреть файл

@ -0,0 +1,3 @@
@set PS1UnderCmd=1
powershell.exe -ExecutionPolicy bypass -Command "& '%~dpn0.ps1'" %*
@set PS1UnderCmd=

61
init.ps1 Normal file
Просмотреть файл

@ -0,0 +1,61 @@
<#
.SYNOPSIS
Installs dependencies required to build and test the projects in this repository.
.DESCRIPTION
This MAY not require elevation, as the SDK and runtimes are installed locally to this repo location,
unless `-InstallLocality machine` is specified.
.PARAMETER InstallLocality
A value indicating whether dependencies should be installed locally to the repo or at a per-user location.
Per-user allows sharing the installed dependencies across repositories and allows use of a shared expanded package cache.
Visual Studio will only notice and use these SDKs/runtimes if VS is launched from the environment that runs this script.
Per-repo allows for high isolation, allowing for a more precise recreation of the environment within an Azure Pipelines build.
When using 'repo', environment variables are set to cause the locally installed dotnet SDK to be used.
Per-repo can lead to file locking issues when dotnet.exe is left running as a build server and can be mitigated by running `dotnet build-server shutdown`.
Per-machine requires elevation and will download and install all SDKs and runtimes to machine-wide locations so all applications can find it.
.PARAMETER NoPrerequisites
Skips the installation of prerequisite software (e.g. SDKs, tools).
.PARAMETER NoRestore
Skips the package restore step.
.PARAMETER AccessToken
An optional access token for authenticating to Azure Artifacts authenticated feeds.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param (
[ValidateSet('repo','user','machine')]
[string]$InstallLocality='user',
[Parameter()]
[switch]$NoPrerequisites,
[Parameter()]
[switch]$NoRestore,
[Parameter()]
[string]$AccessToken
)
if (!$NoPrerequisites) {
& "$PSScriptRoot\tools\Install-NuGetCredProvider.ps1" -AccessToken $AccessToken
& "$PSScriptRoot\tools\Install-DotNetSdk.ps1" -InstallLocality $InstallLocality
}
# Workaround nuget credential provider bug that causes very unreliable package restores on Azure Pipelines
$env:NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS=20
$env:NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS=20
Push-Location $PSScriptRoot
try {
$HeaderColor = 'Green'
if (!$NoRestore) {
Write-Host "Restoring NuGet packages" -ForegroundColor $HeaderColor
dotnet restore src
if ($lastexitcode -ne 0) {
throw "Failure while restoring packages."
}
}
}
catch {
Write-Error $error[0]
exit $lastexitcode
}
finally {
Pop-Location
}

Просмотреть файл

@ -1,14 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<config>
<add key="repositorypath" value="..\packages" />
<add key="repositorypath" value="packages" />
</config>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="myget.org/F/aarnott" value="https://www.myget.org/F/aarnott/api/v3/index.json" />
<add key="CodeGeneration.Roslyn CI" value="https://ci.appveyor.com/nuget/codegeneration-roslyn" />
<add key="MSBuildSdkExtras CI" value="https://www.myget.org/F/msbuildsdkextras/api/v3/index.json" />
<add key="corefxlab" value="https://dotnet.myget.org/F/dotnet-corefxlab/api/v3/index.json" />
</packageSources>
</configuration>

13
src/.vsconfig Normal file
Просмотреть файл

@ -0,0 +1,13 @@
{
"version": "1.0",
"components": [
"Microsoft.Net.Component.4.7.2.SDK",
"Microsoft.Net.Component.4.7.2.TargetingPack",
"Microsoft.Net.Component.4.8.SDK",
"Microsoft.Net.Component.4.TargetingPack",
"Microsoft.NetCore.Component.SDK",
"Microsoft.VisualStudio.Component.Windows10SDK.17763",
"Microsoft.VisualStudio.Workload.ManagedDesktop",
"Microsoft.VisualStudio.Workload.Universal",
]
}

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AdvApi32\AdvApi32.csproj" />
@ -10,4 +10,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="MSBuild.Sdk.Extras">
<PropertyGroup>
<TargetFrameworks>$(PlatformAndPortableFrameworks);netstandard1.6</TargetFrameworks>
<TargetFrameworks>$(PlatformAndPortableFrameworks);net40;netstandard1.6</TargetFrameworks>
<StoreBanned>true</StoreBanned>
</PropertyGroup>
<ItemGroup>

Просмотреть файл

@ -1,13 +1,13 @@
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if NETFRAMEWORK || NETSTANDARD || PROFILE111
#if NETFRAMEWORK || NETSTANDARD
using System.Runtime.InteropServices;
[module: DefaultCharSet(CharSet.Unicode)]
#if NET45_ORLATER || NETSTANDARD || PROFILE111
#if NET45_ORLATER || NETSTANDARD
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32)]

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BCrypt\BCrypt.csproj" />
@ -10,4 +10,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -280,7 +280,7 @@ public class BCryptFacts
new byte[keyMaterial.Length],
BCryptEncryptFlags.BCRYPT_BLOCK_PADDING);
Assert.Equal(0, plainText.Count);
Assert.Empty(plainText);
}
}
}

Просмотреть файл

@ -130,7 +130,11 @@ namespace PInvoke
{
return new BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO
{
#if NETSTANDARD1_3_ORLATER || NETFX_CORE
cbSize = Marshal.SizeOf<BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO>(),
#else
cbSize = Marshal.SizeOf(typeof(BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO)),
#endif
dwInfoVersion = BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION,
};
}

Просмотреть файл

@ -79,7 +79,11 @@ namespace PInvoke
private byte[] AddHeaderToKey(byte[] keyMaterial)
{
#if NETSTANDARD1_3_ORLATER || NETFX_CORE
int headerLength = Marshal.SizeOf<BCRYPT_KEY_DATA_BLOB_HEADER>();
#else
int headerLength = Marshal.SizeOf(typeof(BCRYPT_KEY_DATA_BLOB_HEADER));
#endif
byte[] keyWithHeader = new byte[headerLength + keyMaterial.Length];
Array.Copy(BitConverter.GetBytes((uint)this.dwMagic), keyWithHeader, sizeof(uint));
Array.Copy(BitConverter.GetBytes(this.dwVersion), 0, keyWithHeader, sizeof(uint), sizeof(uint));

Просмотреть файл

@ -707,7 +707,11 @@ namespace PInvoke
}
finally
{
#if NETFX_CORE
Marshal.DestroyStructure<T>(new IntPtr(valueBuffer));
#else
Marshal.DestroyStructure(new IntPtr(valueBuffer), typeof(T));
#endif
}
}
}
@ -745,7 +749,11 @@ namespace PInvoke
fixed (byte* pValue = value.Array)
{
IntPtr pValuePtr = new IntPtr(pValue + value.Offset);
#if NETSTANDARD1_3_ORLATER || NETFX_CORE
return Marshal.PtrToStructure<T>(pValuePtr);
#else
return (T)Marshal.PtrToStructure(pValuePtr, typeof(T));
#endif
}
}
}

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Crypt32\Crypt32.csproj" />
@ -12,4 +12,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DbgHelp\DbgHelp.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,18 +1,23 @@
<Project>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<BaseIntermediateOutputPath>$(MSBuildThisFileDirectory)..\obj\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
<OutputPath>$(MSBuildThisFileDirectory)..\bin\$(Configuration)\</OutputPath>
<RepoRootPath>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\'))</RepoRootPath>
<BaseIntermediateOutputPath>$(RepoRootPath)obj\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
<BaseOutputPath Condition=" '$(BaseOutputPath)' == '' ">$(RepoRootPath)bin\</BaseOutputPath>
<PackageOutputPath>$(RepoRootPath)bin\$(Configuration)\Packages\</PackageOutputPath>
<DesktopOnlyFrameworks>net45;net40;net20</DesktopOnlyFrameworks>
<PlatformSpecificFrameworks>$(DesktopOnlyFrameworks);win8</PlatformSpecificFrameworks>
<LangVersion>8.0</LangVersion>
<!-- <Nullable>enable</Nullable> -->
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<DesktopOnlyFrameworks>net45;net20</DesktopOnlyFrameworks>
<PlatformSpecificFrameworks>$(DesktopOnlyFrameworks);uap10.0</PlatformSpecificFrameworks> <!-- win8 -->
<!-- Target frameworks beyond .NET Standard 1.1 are added to individual projects on an as-needed basis. -->
<PortableOnlyFrameworks>netstandard1.1;portable-net40+win8+wpa81;portable-net45+win8+wpa81</PortableOnlyFrameworks>
<PortableOnlyFrameworks>netstandard1.1</PortableOnlyFrameworks>
<PlatformAndPortableFrameworks>$(PortableOnlyFrameworks);$(PlatformSpecificFrameworks)</PlatformAndPortableFrameworks>
<TargetPlatformMinVersion Condition=" '$(TargetFramework)' == 'win8' ">8.0</TargetPlatformMinVersion>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Title>PInvoke.$(MSBuildProjectName)</Title>
<Authors>Andrew Arnott</Authors>
<Summary>P/Invoke methods for the Windows $(MSBuildProjectName).dll.</Summary>
@ -20,13 +25,17 @@
<PackageProjectUrl>https://github.com/AArnott/pinvoke</PackageProjectUrl>
<Copyright>Copyright © $(Authors)</Copyright>
<Tags>pinvoke .net pcl</Tags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<NoWarn>CS1591</NoWarn>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)PInvoke.ruleset</CodeAnalysisRuleSet>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)opensource.snk</AssemblyOriginatorKeyFile>
<DebugType>portable</DebugType>
<IsTestProject>$(MSBuildProjectName.Contains('Test'))</IsTestProject>
<IsCodeGenerationProject Condition=" $(MSBuildProjectName.Contains('CodeGeneration')) ">true</IsCodeGenerationProject>
@ -34,7 +43,8 @@
<IsPackable Condition=" '$(IsTestProject)' == 'true' or '$(IsCodeGenerationProject)' == 'true' ">false</IsPackable>
<CodeGenerationPackageVersion>0.4.74</CodeGenerationPackageVersion>
<NerdbankGitVersioningPackageVersion>2.2.13</NerdbankGitVersioningPackageVersion>
<ProduceReferenceAssembly Condition=" '$(IsTestProject)' != 'true' ">true</ProduceReferenceAssembly>
</PropertyGroup>
<PropertyGroup Condition=" '$(IsCodeGenerationProject)' != 'true' ">
@ -43,62 +53,55 @@
</PropertyGroup>
<PropertyGroup Condition=" '$(IsTestProject)' == 'true' ">
<OutputPath>$(MSBuildThisFileDirectory)..\bin\$(Configuration)\tests\$(MSBuildProjectName)\</OutputPath>
<OutputPath>$(RepoRootPath)bin\$(Configuration)\tests\$(MSBuildProjectName)\</OutputPath>
<RootNamespace />
<CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)PInvoke.Tests.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup Condition=" '$(IsTestProject)' != 'true' ">
<PackageReference Include="SourceLink.Create.GitHub" Version="2.0.2" PrivateAssets="all" />
<DotNetCliToolReference Include="dotnet-sourcelink-git" Version="2.0.2" />
</ItemGroup>
<ItemDefinitionGroup>
<Compile>
<Generator>MSBuild:GenerateCodeFromAttributes</Generator>
</Compile>
<!-- We build all libraries to a common directory, so avoid trying to copy P2P refs to the directory
to avoid wasting time with file collisions and build warnings. -->
<ProjectReference Condition=" '$(IsTestProject)' != 'true' ">
<!-- Sadly, enabling this optimization breaks loading the assembly later for exporting p/invoke method coverage. -->
<!-- <Private>false</Private> -->
</ProjectReference>
</ItemDefinitionGroup>
<ItemGroup>
<GeneratorAssemblySearchPaths Include="$(MSBuildThisFileDirectory)..\bin\$(Configuration)\netstandard1.6\" />
<GeneratorAssemblySearchPaths Include="$(RepoRootPath)bin\$(Configuration)\netstandard1.6\" />
<AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json"/>
<None Include="$(MSBuildProjectName).exports.txt" Condition=" Exists('$(MSBuildProjectName).exports.txt') and '$(TargetFramework)' == 'net45' ">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Nerdbank.GitVersioning" Version="$(NerdbankGitVersioningPackageVersion)" PrivateAssets="all" />
<!-- <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.4" PrivateAssets="all" /> -->
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0-preview.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" PrivateAssets="All" />
<PackageReference Include="Nerdbank.GitVersioning" Version="3.0.26" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2" PrivateAssets="all" />
</ItemGroup>
<ItemGroup Condition=" '$(IsCodeGenerationProject)' != 'true' ">
<PackageReference Include="CodeGeneration.Roslyn.BuildTime" Version="$(CodeGenerationPackageVersion)" PrivateAssets="all" />
<DotNetCliToolReference Include="dotnet-codegen" Version="$(CodeGenerationPackageVersion)" />
<ProjectReference Include="..\CodeGenerationAttributes\CodeGenerationAttributes.csproj" PrivateAssets="all" />
<ProjectReference Include="..\CodeGenerationAttributes\CodeGenerationAttributes.csproj" PrivateAssets="all">
<Private>false</Private>
</ProjectReference>
<ProjectReference Include="..\CodeGeneration\CodeGeneration.csproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
<SkipGetTargetFrameworkProperties>true</SkipGetTargetFrameworkProperties>
<UndefineProperties>TargetFramework</UndefineProperties>
<Private>false</Private>
</ProjectReference>
</ItemGroup>
<ItemGroup Condition=" '$(IsTestProject)' == 'true' ">
<PackageReference Include="xunit" Version="2.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
<PackageReference Include="xunit.runner.console" Version="2.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="coverlet.msbuild" Version="2.6.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="xunit.runner.console" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="xunit" Version="2.4.1" />
</ItemGroup>
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' == 'true' ">
<Import Project="$(UserProfile)\.nuget\packages\nerdbank.gitversioning\$(NerdbankGitVersioningPackageVersion)\buildCrossTargeting\Nerdbank.GitVersioning.targets"
Condition="Exists('$(UserProfile)\.nuget\packages\nerdbank.gitversioning\$(NerdbankGitVersioningPackageVersion)\buildCrossTargeting\Nerdbank.GitVersioning.targets')" />
</ImportGroup>
<Target Name="FixUpVersion"
BeforeTargets="_GenerateRestoreProjectSpec"
DependsOnTargets="GetBuildVersion"
Condition=" '$(NerdbankGitVersioningTasksPath)' != '' " />
<Target Name="SetNuSpecProperties" BeforeTargets="GenerateNuspec" DependsOnTargets="GetBuildVersion">
<PropertyGroup>
<PackageLicenseUrl>https://raw.githubusercontent.com/AArnott/pinvoke/$(GitCommitIdShort)/LICENSE</PackageLicenseUrl>
</PropertyGroup>
</Target>
</Project>

Просмотреть файл

@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<RootNamespace Condition=" '$(IsTestProject)' == 'true' " />
<ExcludeStoreBannedAPIs Condition=" '$(TargetPlatformIdentifier)' == 'Windows' and '$(TargetPlatformVersion)' >= 8.0 ">true</ExcludeStoreBannedAPIs>
<ExcludeStoreBannedAPIs Condition=" ('$(TargetPlatformIdentifier)' == 'Windows' or '$(TargetPlatformIdentifier)' == 'UAP') and '$(TargetPlatformVersion)' >= 8.0 ">true</ExcludeStoreBannedAPIs>
<DefineConstants Condition=" '$(ExcludeStoreBannedAPIs)' != 'true' ">$(DefineConstants);IncludeStoreBannedAPIs</DefineConstants>
<DefineConstants Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' or ('$(TargetFrameworkIdentifier)' == '.NETStandard' and '$(_TargetFrameworkVersionWithoutV)' >= 2.0) ">$(DefineConstants);Serialization</DefineConstants>
<DefineConstants Condition=" '$(TargetFrameworkIdentifier)' == '.NETStandard' and '$(_TargetFrameworkVersionWithoutV)' >= 1.3 ">$(DefineConstants);NETSTANDARD1_3_ORLATER</DefineConstants>
@ -13,6 +13,13 @@
<DefineConstants Condition=" '$(TargetFrameworkIdentifier)' != '.NETFramework' ">$(DefineConstants);APISets</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(IsTestProject)' == 'true' ">
<CoverletOutputFormat>cobertura</CoverletOutputFormat>
<Exclude>[xunit.*]*</Exclude>
<!-- Ensure we preserve each coverlet output file per target framework: https://github.com/tonerdo/coverlet/issues/177 -->
<CoverletOutput>$(OutputPath)/</CoverletOutput>
</PropertyGroup>
<ItemGroup>
<Compile Remove="storebanned\**" Condition=" '$(ExcludeStoreBannedAPIs)' == 'true' " />
<Compile Remove="**" Condition=" '$(ExcludeStoreBannedAPIs)' == 'true' and '$(StoreBanned)' == 'true' " />

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DwmApi\DwmApi.csproj" />
@ -9,4 +9,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Fusion\Fusion.csproj" />
@ -9,4 +9,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -8,13 +8,13 @@
<ProjectReference Include="..\Windows.Core\Windows.Core.csproj" />
</ItemGroup>
<ItemGroup>
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.6.1\Lib\um\x86\mscoree.tlb">
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.7.2\Lib\um\x86\mscoree.tlb">
<Visible>false</Visible>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMFileReference>
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.6.1\Lib\um\x86\cordebug.tlb">
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.7.2\Lib\um\x86\cordebug.tlb">
<Visible>false</Visible>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMFileReference>
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Hid\Hid.csproj" />
@ -9,4 +9,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DbgHelp\DbgHelp.csproj" />
@ -9,4 +9,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -9,7 +9,9 @@ using static PInvoke.ImageHlp;
public class ImageHlpFacts
{
[Fact(Skip = "Fails on appveyor")]
[Fact]
[Trait("skiponcloud", "true")]
[Trait("TestCategory", "FailsInCloudTest")]
public void MapAndLoadTest()
{
LOADED_IMAGE imageData;

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46;netcoreapp2.1</TargetFrameworks>
<TargetFrameworks>net472;netcoreapp2.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Kernel32\Kernel32.csproj" />

Просмотреть файл

@ -49,7 +49,7 @@ namespace PInvoke
{
return new SECURITY_ATTRIBUTES
{
#if NETSTANDARD1_3_ORLATER
#if NETSTANDARD1_3_ORLATER || NETFX_CORE
nLength = Marshal.SizeOf<SECURITY_ATTRIBUTES>(),
#else
nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)),

Просмотреть файл

@ -90,7 +90,7 @@ namespace PInvoke
: hexCode;
string insert = $"NT_STATUS {GetSeverityString(status)}: {statusAsString}";
string message = null;
#if !WINDOWS8
#if !WINDOWS8 && !WINDOWS_UWP
message = status.GetMessage();
#endif

Просмотреть файл

@ -1,7 +1,7 @@
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if NETSTANDARD1_1 || NETPORTABLE || WINDOWS8
#if NETSTANDARD1_1 || NETPORTABLE || WINDOWS8 || WINDOWS_UWP
namespace Microsoft.Win32.SafeHandles
{

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
<ResolveComReferenceSilent>true</ResolveComReferenceSilent>
</PropertyGroup>
<ItemGroup>
@ -9,7 +9,7 @@
<ProjectReference Include="..\Windows.Core\Windows.Core.csproj" />
</ItemGroup>
<ItemGroup>
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.6.1\Lib\um\x86\metahost.tlb">
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.7.2\Lib\um\x86\metahost.tlb">
<Visible>false</Visible>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMFileReference>
@ -20,4 +20,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -9,7 +9,7 @@
<ProjectReference Include="..\Kernel32\Kernel32.csproj" />
</ItemGroup>
<ItemGroup>
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.6.1\Lib\um\x86\metahost.tlb">
<COMFileReference Include="$(MSBuildProgramFiles32)\Windows Kits\NETFXSDK\4.7.2\Lib\um\x86\metahost.tlb">
<Visible>false</Visible>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMFileReference>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Windows.Core\Windows.Core.csproj" />

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Msi\Msi.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\NCrypt\NCrypt.csproj" />
@ -13,4 +13,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -57,7 +57,11 @@ namespace PInvoke
{
return new NCRYPT_KEY_BLOB_HEADER
{
#if NETSTANDARD1_3_ORLATER || NETFX_CORE
cbSize = Marshal.SizeOf<NCRYPT_KEY_BLOB_HEADER>(),
#else
cbSize = Marshal.SizeOf(typeof(NCRYPT_KEY_BLOB_HEADER)),
#endif
};
}
}

Просмотреть файл

@ -220,7 +220,11 @@ namespace PInvoke
{
fixed (byte* pValue = value)
{
#if NETSTANDARD1_3_ORLATER || NETFX_CORE
return Marshal.PtrToStructure<T>(new IntPtr(pValue));
#else
return (T)Marshal.PtrToStructure(new IntPtr(pValue), typeof(T));
#endif
}
}
}
@ -266,7 +270,11 @@ namespace PInvoke
}
finally
{
#if NETFX_CORE
Marshal.DestroyStructure<T>(new IntPtr(valueBuffer));
#else
Marshal.DestroyStructure(new IntPtr(valueBuffer), typeof(T));
#endif
}
}
}

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\NtDll\NtDll.csproj" />
@ -9,4 +9,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\NetApi32\NetApi32.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Windows.Core\Windows.Core.csproj" />

Просмотреть файл

@ -1,23 +1,23 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27004.2005
# Visual Studio Version 16
VisualStudioVersion = 16.0.29410.161
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CD09C869-A027-4F21-B78F-22CF072B9C7F}"
ProjectSection(SolutionItems) = preProject
..\.editorconfig = ..\.editorconfig
..\.gitignore = ..\.gitignore
..\templates\AddNewCoreLibrary.ps1 = ..\templates\AddNewCoreLibrary.ps1
..\templates\AddNewLibrary.ps1 = ..\templates\AddNewLibrary.ps1
..\appveyor.yml = ..\appveyor.yml
..\build.ps1 = ..\build.ps1
..\CONTRIBUTING.md = ..\CONTRIBUTING.md
..\CONTRIBUTORS.md = ..\CONTRIBUTORS.md
..\templates\CreateExportsTxtFile.ps1 = ..\templates\CreateExportsTxtFile.ps1
..\LICENSE = ..\LICENSE
nuget.config = nuget.config
..\nuget.config = ..\nuget.config
..\README.md = ..\README.md
stylecop.json = stylecop.json
..\tools\Update-CoverageReport.ps1 = ..\tools\Update-CoverageReport.ps1
version.json = version.json
..\version.json = ..\version.json
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BCrypt", "BCrypt\BCrypt.csproj", "{9CE056E3-5D53-4092-97CC-78826A4D1C14}"

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Psapi\Psapi.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SHCore\SHCore.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SetupApi\SetupApi.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Shell32\Shell32.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\User32\User32.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -60,6 +60,7 @@ public partial class User32Facts
[Fact]
[Trait("skiponcloud", "true")]
[Trait("TestCategory", "FailsInCloudTest")]
public void GetWindowTextHelper_WithNonzeroLastError()
{
IntPtr hwnd = CreateWindow(
@ -146,4 +147,4 @@ public partial class User32Facts
}
}
}
}
}

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Userenv\Userenv.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\UxTheme\UxTheme.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Windows.Core\Windows.Core.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="MSBuild.Sdk.Extras">
<PropertyGroup>
<TargetFrameworks>$(PortableOnlyFrameworks);net20;net35;netstandard2.0</TargetFrameworks>
<TargetFrameworks>$(PortableOnlyFrameworks);net20;netstandard2.0</TargetFrameworks>
<Summary>P/Invoke types for common Windows APIs.</Summary>
<Description>P/Invoke types for common Windows APIs.</Description>
</PropertyGroup>

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\WtsApi32\WtsApi32.csproj" />
@ -8,4 +8,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -1,8 +0,0 @@
{
"sdk": {
"version": "2.1.300"
},
"msbuild-sdks": {
"MSBuild.Sdk.Extras": "1.6.52"
}
}

Просмотреть файл

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Windows.Core\Windows.Core.csproj" />
@ -9,4 +9,4 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project>
</Project>

Просмотреть файл

@ -24,6 +24,8 @@ if (!$NoBuild) {
$Shields = & "$PSScriptRoot\Get-Shields.ps1" -Directory "$PSScriptRoot\..\bin\$Configuration"
$version = & (& "$PSScriptRoot\..\azure-pipelines\Get-nbgv.ps1") get-version -p "$PSScriptRoot\..\src" -v SemVer2
$commit = & (& "$PSScriptRoot\..\azure-pipelines\Get-nbgv.ps1") get-version -p "$PSScriptRoot\..\src" -v GitCommitId
$report = "# P/Invoke coverage report
Coverage | Package
@ -36,6 +38,10 @@ $Shields |% {
"
}
$report += "
Produced for v$version ($commit)
"
if ($OutFile) {
Set-Content -Path $OutFile -Value $report
} else {

196
tools/Install-DotNetSdk.ps1 Normal file
Просмотреть файл

@ -0,0 +1,196 @@
<#
.SYNOPSIS
Installs the .NET SDK specified in the global.json file at the root of this repository,
along with supporting .NET Core runtimes used for testing.
.DESCRIPTION
This MAY not require elevation, as the SDK and runtimes are installed locally to this repo location,
unless `-InstallLocality machine` is specified.
.PARAMETER InstallLocality
A value indicating whether dependencies should be installed locally to the repo or at a per-user location.
Per-user allows sharing the installed dependencies across repositories and allows use of a shared expanded package cache.
Visual Studio will only notice and use these SDKs/runtimes if VS is launched from the environment that runs this script.
Per-repo allows for high isolation, allowing for a more precise recreation of the environment within an Azure Pipelines build.
When using 'repo', environment variables are set to cause the locally installed dotnet SDK to be used.
Per-repo can lead to file locking issues when dotnet.exe is left running as a build server and can be mitigated by running `dotnet build-server shutdown`.
Per-machine requires elevation and will download and install all SDKs and runtimes to machine-wide locations so all applications can find it.
#>
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
Param (
[ValidateSet('repo','user','machine')]
[string]$InstallLocality='user'
)
$DotNetInstallScriptRoot = "$PSScriptRoot/../obj/tools"
if (!(Test-Path $DotNetInstallScriptRoot)) { New-Item -ItemType Directory -Path $DotNetInstallScriptRoot | Out-Null }
$DotNetInstallScriptRoot = Resolve-Path $DotNetInstallScriptRoot
# Look up actual required .NET Core SDK version from global.json
$sdkVersion = & "$PSScriptRoot/../azure-pipelines/variables/DotNetSdkVersion.ps1"
# Search for all .NET Core runtime versions referenced from MSBuild projects and arrange to install them.
$runtimeVersions = @()
Get-ChildItem "$PSScriptRoot\..\src\*.*proj" -Recurse |% {
$projXml = [xml](Get-Content -Path $_)
$targetFrameworks = $projXml.Project.PropertyGroup.TargetFramework
if (!$targetFrameworks) {
$targetFrameworks = $projXml.Project.PropertyGroup.TargetFrameworks
if ($targetFrameworks) {
$targetFrameworks = $targetFrameworks -Split ';'
}
}
$targetFrameworks |? { $_ -match 'netcoreapp(\d+\.\d+)' } |% {
$runtimeVersions += $Matches[1]
}
}
Function Get-FileFromWeb([Uri]$Uri, $OutDir) {
$OutFile = Join-Path $OutDir $Uri.Segments[-1]
if (!(Test-Path $OutFile)) {
Write-Verbose "Downloading $Uri..."
try {
(New-Object System.Net.WebClient).DownloadFile($Uri, $OutFile)
} finally {
# This try/finally causes the script to abort
}
}
$OutFile
}
Function Get-InstallerExe($Version, [switch]$Runtime) {
$sdkOrRuntime = 'Sdk'
if ($Runtime) { $sdkOrRuntime = 'Runtime' }
# Get the latest/actual version for the specified one
if (([Version]$Version).Build -eq -1) {
$versionInfo = -Split (Invoke-WebRequest -Uri "https://dotnetcli.blob.core.windows.net/dotnet/$sdkOrRuntime/$Version/latest.version" -UseBasicParsing)
$Version = $versionInfo[-1]
}
Get-FileFromWeb -Uri "https://dotnetcli.blob.core.windows.net/dotnet/$sdkOrRuntime/$Version/dotnet-$($sdkOrRuntime.ToLowerInvariant())-$Version-win-x64.exe" -OutDir "$DotNetInstallScriptRoot"
}
Function Install-DotNet($Version, [switch]$Runtime) {
if ($Runtime) { $sdkSubstring = '' } else { $sdkSubstring = 'SDK ' }
Write-Host "Downloading .NET Core $sdkSubstring$Version..."
$Installer = Get-InstallerExe -Version $Version -Runtime:$Runtime
Write-Host "Installing .NET Core $sdkSubstring$Version..."
cmd /c start /wait $Installer /install /quiet
if ($LASTEXITCODE -ne 0) {
throw "Failure to install .NET Core SDK"
}
}
if ($InstallLocality -eq 'machine') {
if ($IsMacOS -or $IsLinux) {
Write-Error "Installing the .NET Core SDK or runtime at a machine-wide location is only supported by this script on Windows."
exit 1
}
if ($PSCmdlet.ShouldProcess(".NET Core SDK $sdkVersion", "Install")) {
Install-DotNet -Version $sdkVersion
}
$runtimeVersions |% {
if ($PSCmdlet.ShouldProcess(".NET Core runtime $_", "Install")) {
Install-DotNet -Version $_ -Runtime
}
}
return
}
$switches = @(
'-Architecture','x64'
)
$envVars = @{
# For locally installed dotnet, skip first time experience which takes a long time
'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' = 'true';
}
if ($InstallLocality -eq 'repo') {
$DotNetInstallDir = "$DotNetInstallScriptRoot/.dotnet"
} elseif ($env:AGENT_TOOLSDIRECTORY) {
$DotNetInstallDir = "$env:AGENT_TOOLSDIRECTORY/dotnet"
} else {
$DotNetInstallDir = Join-Path $HOME .dotnet
}
Write-Host "Installing .NET Core SDK and runtimes to $DotNetInstallDir" -ForegroundColor Blue
if ($DotNetInstallDir) {
$switches += '-InstallDir',$DotNetInstallDir
$envVars['DOTNET_MULTILEVEL_LOOKUP'] = '0'
$envVars['DOTNET_ROOT'] = $DotNetInstallDir
}
if ($IsMacOS -or $IsLinux) {
$DownloadUri = "https://dot.net/v1/dotnet-install.sh"
$DotNetInstallScriptPath = "$DotNetInstallScriptRoot/dotnet-install.sh"
} else {
$DownloadUri = "https://dot.net/v1/dotnet-install.ps1"
$DotNetInstallScriptPath = "$DotNetInstallScriptRoot/dotnet-install.ps1"
}
if (-not (Test-Path $DotNetInstallScriptPath)) {
Invoke-WebRequest -Uri $DownloadUri -OutFile $DotNetInstallScriptPath -UseBasicParsing
if ($IsMacOS -or $IsLinux) {
chmod +x $DotNetInstallScriptPath
}
}
if ($PSCmdlet.ShouldProcess(".NET Core SDK $sdkVersion", "Install")) {
Invoke-Expression -Command "$DotNetInstallScriptPath -Version $sdkVersion $switches"
} else {
Invoke-Expression -Command "$DotNetInstallScriptPath -Version $sdkVersion $switches -DryRun"
}
$switches += '-Runtime','dotnet'
$runtimeVersions | Get-Unique |% {
if ($PSCmdlet.ShouldProcess(".NET Core runtime $_", "Install")) {
Invoke-Expression -Command "$DotNetInstallScriptPath -Channel $_ $switches"
} else {
Invoke-Expression -Command "$DotNetInstallScriptPath -Channel $_ $switches -DryRun"
}
}
if ($PSCmdlet.ShouldProcess("Set DOTNET environment variables to discover these installed runtimes?")) {
if ($env:TF_BUILD) {
Write-Host "Azure Pipelines detected. Logging commands will be used to propagate environment variables and prepend path."
}
if ($IsMacOS -or $IsLinux) {
$envVars['PATH'] = "${DotNetInstallDir}:$env:PATH"
} else {
$envVars['PATH'] = "$DotNetInstallDir;$env:PATH"
}
$envVars.GetEnumerator() |% {
Set-Item -Path env:$($_.Key) -Value $_.Value
# If we're running in Azure Pipelines, set these environment variables
if ($env:TF_BUILD) {
Write-Host "##vso[task.setvariable variable=$($_.Key);]$($_.Value)"
}
}
if ($env:TF_BUILD) {
Write-Host "##vso[task.prependpath]$DotNetInstallDir"
}
}
if ($env:PS1UnderCmd -eq '1') {
Write-Warning "Environment variable changes will be lost because you're running under cmd.exe. Run these commands manually:"
$envVars.GetEnumerator() |% {
if ($_.Key -eq 'PATH') {
# Special case this one for readability
Write-Host "SET PATH=$DotNetInstallDir;%PATH%"
} else {
Write-Host "SET $($_.Key)=$($_.Value)"
}
}
} else {
Write-Host "Environment variables set:" -ForegroundColor Blue
$envVars
}

Просмотреть файл

@ -0,0 +1,62 @@
<#
.SYNOPSIS
Downloads and installs the Microsoft Artifacts Credential Provider
from https://github.com/microsoft/artifacts-credprovider
to assist in authenticating to Azure Artifact feeds in interactive development
or unattended build agents.
.PARAMETER AccessToken
An optional access token for authenticating to Azure Artifacts authenticated feeds.
#>
[CmdletBinding()]
Param (
[Parameter()]
[string]$AccessToken
)
$toolsPath = & "$PSScriptRoot\..\azure-pipelines\Get-TempToolsPath.ps1"
if ($IsMacOS -or $IsLinux) {
$installerScript = "installcredprovider.sh"
$sourceUrl = "https://raw.githubusercontent.com/microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh"
} else {
$installerScript = "installcredprovider.ps1"
$sourceUrl = "https://raw.githubusercontent.com/microsoft/artifacts-credprovider/master/helpers/installcredprovider.ps1"
}
$installerScript = Join-Path $toolsPath $installerScript
if (!(Test-Path $installerScript)) {
Invoke-WebRequest $sourceUrl -OutFile $installerScript
}
$installerScript = (Resolve-Path $installerScript).Path
if ($IsMacOS -or $IsLinux) {
chmod u+x $installerScript
}
& $installerScript
if ($AccessToken) {
$endpoints = @()
$nugetConfig = [xml](Get-Content -Path "$PSScriptRoot\..\nuget.config")
$nugetConfig.configuration.packageSources.add |? { ($_.value -match '^https://pkgs\.dev\.azure\.com/') -or ($_.value -match '^https://[\w\-]+\.pkgs\.visualstudio\.com/') } |% {
$endpoint = New-Object -TypeName PSObject
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name endpoint -Value $_.value
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name username -Value ado
Add-Member -InputObject $endpoint -MemberType NoteProperty -Name password -Value $AccessToken
$endpoints += $endpoint
}
$auth = New-Object -TypeName PSObject
Add-Member -InputObject $auth -MemberType NoteProperty -Name endpointCredentials -Value $endpoints
$authJson = ConvertTo-Json -InputObject $auth
$envVars = @{
'VSS_NUGET_EXTERNAL_FEED_ENDPOINTS'=$authJson;
}
& "$PSScriptRoot\..\azure-pipelines\Set-EnvVars.ps1" -Variables $envVars | Out-Null
}

Просмотреть файл

@ -1,13 +1,8 @@
{
"$schema": "https://raw.githubusercontent.com/AArnott/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
"version": "0.5",
"version": "0.6",
"publicReleaseRefSpec": [
"^refs/heads/master$", // we release out of master
"^refs/tags/v\\d+\\.\\d+" // we also release tags starting with vN.N
],
"cloudBuild": {
"buildNumber": {
"enabled": true
}
}
]
}