├── .gitignore
├── Demo Console App
├── Demo Console App.csproj
└── Program.cs
├── LICENSE
├── README.md
├── Solution.sln
└── WindowsPackageManager Interop
├── Exceptions
└── WinGetConfigurationException.cs
├── NativeMethods.txt
├── WindowsPackageManager Interop.csproj
└── WindowsPackageManager
├── ClassModel.cs
├── ClassesDefinition.cs
├── ClsidContext.cs
├── WindowsPackageManagerElevatedFactory.cs
├── WindowsPackageManagerFactory.cs
└── WindowsPackageManagerStandardFactory.cs
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
--------------------------------------------------------------------------------
/Demo Console App/Demo Console App.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0-windows10.0.19041.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Demo Console App/Program.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Principal;
2 |
3 | // Include WinGet Namespace
4 | using WindowsPackageManager.Interop;
5 |
6 | namespace WingetTest
7 | {
8 | internal class Program
9 | {
10 | static public void Main(string[] args)
11 | {
12 | while(true)
13 | {
14 | Console.WriteLine(" ");
15 | Console.Write("Enter search query: ");
16 | string? Query = Console.ReadLine();
17 | if(Query == null || Query == "")
18 | break;
19 |
20 | FindPackagesForQuery(Query).Wait();
21 | }
22 | }
23 |
24 | private static async Task FindPackagesForQuery(string Query)
25 | {
26 | WindowsPackageManagerFactory WinGetFactory;
27 | bool IsAdministrator = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
28 |
29 | // If the user is an administrator, use the elevated factory. Otherwhise COM will crash
30 | if(IsAdministrator)
31 | WinGetFactory = new WindowsPackageManagerElevatedFactory();
32 | else
33 | WinGetFactory = new WindowsPackageManagerStandardFactory();
34 |
35 | // Create Package Manager and get available catalogs
36 | var Manager = WinGetFactory.CreatePackageManager();
37 | var AvailableCatalogs = Manager.GetPackageCatalogs();
38 |
39 | foreach (var Catalog in AvailableCatalogs.ToArray())
40 | {
41 | // Create a filter to search for packages
42 | var FilterList = WinGetFactory.CreateFindPackagesOptions();
43 |
44 | // Add the query to the filter
45 | var NameFilter = WinGetFactory.CreatePackageMatchFilter();
46 | NameFilter.Field = Microsoft.Management.Deployment.PackageMatchField.Name;
47 | NameFilter.Value = Query;
48 | FilterList.Filters.Add(NameFilter);
49 |
50 | // Find the packages with the filters
51 | var SearchResults = await Catalog.Connect().PackageCatalog.FindPackagesAsync(FilterList);
52 | foreach (var Match in SearchResults.Matches.ToArray())
53 | {
54 | // Print the packages
55 | var Package = Match.CatalogPackage;
56 | Console.WriteLine(Package.Name);
57 | }
58 | }
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 | SOFTWARE.
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Using WinGet APIs from C# .NET
2 | Minimal example on how to use WinGet COM APIs from C#.NET.
3 |
4 | The code on the project named `WindowsPackageManager Interop` was extracted and modified from [Dev Home](https://github.com/microsoft/devhome/).
5 |
6 | ## Usage instructions:
7 | 1. Add the `WindowsPackageManager Interop.csproj` to your solution
8 | 2. Import the `WindowsPackageManager.Interop` Namespace.
9 | 3. Create a WinGet Package Manager Factory using the `WindowsPackageManagerStandardFactory` class.
10 | 4. Operate WinGet as stated on the official documentation: https://github.com/microsoft/winget-cli/blob/master/doc/specs/%23888%20-%20Com%20Api.md
11 | > [!WARNING]
12 | > The `CreateAppInstaller()` WinRT function does not exist. `CreatePackageManager()` must be used instead.
13 |
14 |
15 |
16 | ## ⚠️Important notes about running with admin rights⚠️
17 | If an elevated process initializes WinGet with the `WindowsPackageManagerStandardFactory()` class, the method `CreatePackageManager()` will crash. The class `WindowsPackageManagerElevatedFactory()` must be used instead.
18 |
19 | However, under certain scenarios (for example, Unpackaged, self-contained AppSdk executable with RegFree-WinRT enabled), the `WindowsPackageManagerElevatedFactory()` method may crash your program (no exception, just a hard crash, the bug report can be seen here: https://github.com/microsoft/winget-cli/issues/4377).
20 |
21 | In such case, it may be needed to use the `WindowsPackageManagerStandardFactory()` class, but modifying the CreateInstance method as shown [here (this is how it works on UniGetUI)](https://github.com/marticliment/UniGetUI/blob/9d73f284edfd0e9c26a2a8d3d72187180ea3af23/src/WindowsPackageManager.Interop/WindowsPackageManager/WindowsPackageManagerStandardFactory.cs#L23-L29) so that the undocumented `CLSCTX.CLSCTX_ALLOW_LOWER_TRUST_REGISTRATION` flag is passed to `PInvoke.CoCreateInstance`.
22 |
23 |
24 |
25 | # Usage example
26 | The following example can be found on the `Demo Console App` project on this same repository.
27 | The code prompts the user for a query and prints the found WinGet packages, filtering them by name.
28 | ```cs
29 | using System.Security.Principal;
30 |
31 | // Include WinGet Namespace
32 | using WindowsPackageManager.Interop;
33 |
34 | namespace WingetTest
35 | {
36 | internal class Program
37 | {
38 | // Read a query and call the FindPackagesForQuery() method
39 | static public void Main(string[] args)
40 | {
41 | while(true)
42 | {
43 | Console.Write("Enter search query: ");
44 | string? Query = Console.ReadLine();
45 | if(Query == null || Query == "")
46 | break;
47 |
48 | FindPackagesForQuery(Query).Wait();
49 | }
50 | }
51 |
52 | private static async Task FindPackagesForQuery(string Query)
53 | {
54 | WindowsPackageManagerFactory WinGetFactory;
55 | bool IsAdministrator = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
56 |
57 | // If the user is an administrator, use the elevated factory. Otherwhise COM will crash
58 | if(IsAdministrator)
59 | WinGetFactory = new WindowsPackageManagerElevatedFactory();
60 | else
61 | WinGetFactory = new WindowsPackageManagerStandardFactory();
62 |
63 | // Create Package Manager and get available catalogs
64 | var Manager = WinGetFactory.CreatePackageManager();
65 | var AvailableCatalogs = Manager.GetPackageCatalogs();
66 |
67 | foreach (var Catalog in AvailableCatalogs.ToArray())
68 | {
69 | // Create a filter to search for packages
70 | var FilterList = WinGetFactory.CreateFindPackagesOptions();
71 |
72 | // Add the query to the filter
73 | var NameFilter = WinGetFactory.CreatePackageMatchFilter();
74 | NameFilter.Field = Microsoft.Management.Deployment.PackageMatchField.Name;
75 | NameFilter.Value = Query;
76 | FilterList.Filters.Add(NameFilter);
77 |
78 | // Find the packages with the filters
79 | var SearchResults = await Catalog.Connect().PackageCatalog.FindPackagesAsync(FilterList);
80 | foreach (var Match in SearchResults.Matches.ToArray())
81 | {
82 | // Print the packages
83 | var Package = Match.CatalogPackage;
84 | Console.WriteLine(Package.Name);
85 | }
86 | }
87 | }
88 | }
89 | }
90 |
91 | ```
92 |
93 | # Fetching installed packages
94 |
95 | ```csharp
96 | using Microsoft.Management.Deployment;
97 | using System.Security.Principal;
98 | using Windows.ApplicationModel;
99 |
100 |
101 | // Include WinGet Namespace
102 | using WindowsPackageManager.Interop;
103 |
104 | namespace WingetTest
105 | {
106 | internal class Program
107 | {
108 | static public void Main(string[] args)
109 | {
110 | // var WinGetFactory = new WindowsPackageManagerElevatedFactory();
111 | var WinGetFactory = new WindowsPackageManagerStandardFactory();
112 | var WinGetManager = WinGetFactory.CreatePackageManager();
113 |
114 | // CHANGE THIS INDEX TO CHANGE THE SOURCE
115 | int selectedIndex = 0;
116 |
117 | PackageCatalogReference installedSearchCatalogRef;
118 | if (selectedIndex < 0)
119 | {
120 | installedSearchCatalogRef = WinGetManager.GetLocalPackageCatalog(LocalPackageCatalog.InstalledPackages);
121 | }
122 | else
123 | {
124 | PackageCatalogReference selectedRemoteCatalogRef = WinGetManager.GetPackageCatalogs().ToArray().ElementAt(selectedIndex);
125 |
126 | Console.WriteLine($"Searching on package catalog {selectedRemoteCatalogRef.Info.Name} ");
127 | CreateCompositePackageCatalogOptions createCompositePackageCatalogOptions = WinGetFactory.CreateCreateCompositePackageCatalogOptions();
128 | createCompositePackageCatalogOptions.Catalogs.Add(selectedRemoteCatalogRef);
129 | createCompositePackageCatalogOptions.CompositeSearchBehavior = CompositeSearchBehavior.LocalCatalogs;
130 | installedSearchCatalogRef = WinGetManager.CreateCompositePackageCatalog(createCompositePackageCatalogOptions);
131 | }
132 |
133 | var ConnectResult = installedSearchCatalogRef.Connect();
134 | if (ConnectResult.Status != ConnectResultStatus.Ok)
135 | {
136 | throw new Exception("WinGet: Failed to connect to local catalog.");
137 | }
138 |
139 | FindPackagesOptions findPackagesOptions = WinGetFactory.CreateFindPackagesOptions();
140 | PackageMatchFilter filter = WinGetFactory.CreatePackageMatchFilter();
141 | filter.Field = PackageMatchField.Id;
142 | filter.Option = PackageFieldMatchOption.ContainsCaseInsensitive;
143 | filter.Value = "";
144 | findPackagesOptions.Filters.Add(filter);
145 |
146 | var TaskResult = ConnectResult.PackageCatalog.FindPackages(findPackagesOptions);
147 |
148 | Console.WriteLine("Begin enumeration");
149 | foreach (var match in TaskResult.Matches.ToArray())
150 | {
151 | if (match.CatalogPackage.DefaultInstallVersion != null)
152 | Console.WriteLine($"Package {match.CatalogPackage.Name} is available Online: " + match.CatalogPackage.DefaultInstallVersion.PackageCatalog.Info.Name);
153 | //else
154 | //Console.WriteLine("Package is local only: " + match.CatalogPackage.Id);
155 | }
156 | Console.WriteLine("End enumeration");
157 | }
158 | }
159 | }
160 |
161 |
162 | ```
163 |
--------------------------------------------------------------------------------
/Solution.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.10.34707.107
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WindowsPackageManager Interop", "WindowsPackageManager Interop\WindowsPackageManager Interop.csproj", "{39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Demo Console App", "Demo Console App\Demo Console App.csproj", "{D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Debug|arm64 = Debug|arm64
14 | Debug|x64 = Debug|x64
15 | Debug|x86 = Debug|x86
16 | Release|Any CPU = Release|Any CPU
17 | Release|arm64 = Release|arm64
18 | Release|x64 = Release|x64
19 | Release|x86 = Release|x86
20 | EndGlobalSection
21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
22 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|Any CPU.ActiveCfg = Debug|x64
23 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|Any CPU.Build.0 = Debug|x64
24 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|arm64.ActiveCfg = Debug|arm64
25 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|arm64.Build.0 = Debug|arm64
26 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|x64.ActiveCfg = Debug|x64
27 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|x64.Build.0 = Debug|x64
28 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|x86.ActiveCfg = Debug|x86
29 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Debug|x86.Build.0 = Debug|x86
30 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|Any CPU.ActiveCfg = Release|x64
31 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|Any CPU.Build.0 = Release|x64
32 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|arm64.ActiveCfg = Release|arm64
33 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|arm64.Build.0 = Release|arm64
34 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|x64.ActiveCfg = Release|x64
35 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|x64.Build.0 = Release|x64
36 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|x86.ActiveCfg = Release|x86
37 | {39D02ACA-38AC-41B4-8ED4-DC591AAC5B1F}.Release|x86.Build.0 = Release|x86
38 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
39 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|Any CPU.Build.0 = Debug|Any CPU
40 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|arm64.ActiveCfg = Debug|Any CPU
41 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|arm64.Build.0 = Debug|Any CPU
42 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|x64.ActiveCfg = Debug|Any CPU
43 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|x64.Build.0 = Debug|Any CPU
44 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|x86.ActiveCfg = Debug|Any CPU
45 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Debug|x86.Build.0 = Debug|Any CPU
46 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|Any CPU.ActiveCfg = Release|Any CPU
47 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|Any CPU.Build.0 = Release|Any CPU
48 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|arm64.ActiveCfg = Release|Any CPU
49 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|arm64.Build.0 = Release|Any CPU
50 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|x64.ActiveCfg = Release|Any CPU
51 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|x64.Build.0 = Release|Any CPU
52 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|x86.ActiveCfg = Release|Any CPU
53 | {D30DB5C6-8D6E-4EA9-99C5-C3B495C0109C}.Release|x86.Build.0 = Release|Any CPU
54 | EndGlobalSection
55 | GlobalSection(SolutionProperties) = preSolution
56 | HideSolutionNode = FALSE
57 | EndGlobalSection
58 | GlobalSection(ExtensibilityGlobals) = postSolution
59 | SolutionGuid = {E855C1C8-5A5C-45A1-BBD0-5253A0E190F2}
60 | EndGlobalSection
61 | EndGlobal
62 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/Exceptions/WinGetConfigurationException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 |
6 | namespace WindowsPackageManager.Interop;
7 |
8 | public class WinGetConfigurationException : Exception
9 | {
10 | // WinGet Configuration error codes:
11 | // https://github.com/microsoft/winget-cli/blob/master/src/PowerShell/Microsoft.WinGet.Configuration.Engine/Exceptions/ErrorCodes.cs
12 | public const int WingetConfigErrorInvalidConfigurationFile = unchecked((int)0x8A15C001);
13 | public const int WingetConfigErrorInvalidYaml = unchecked((int)0x8A15C002);
14 | public const int WingetConfigErrorInvalidFieldType = unchecked((int)0x8A15C003);
15 | public const int WingetConfigErrorUnknownConfigurationFileVersion = unchecked((int)0x8A15C004);
16 | public const int WingetConfigErrorSetApplyFailed = unchecked((int)0x8A15C005);
17 | public const int WingetConfigErrorDuplicateIdentifier = unchecked((int)0x8A15C006);
18 | public const int WingetConfigErrorMissingDependency = unchecked((int)0x8A15C007);
19 | public const int WingetConfigErrorDependencyUnsatisfied = unchecked((int)0x8A15C008);
20 | public const int WingetConfigErrorAssertionFailed = unchecked((int)0x8A15C009);
21 | public const int WingetConfigErrorManuallySkipped = unchecked((int)0x8A15C00A);
22 | public const int WingetConfigErrorWarningNotAccepted = unchecked((int)0x8A15C00B);
23 | public const int WingetConfigErrorSetDependencyCycle = unchecked((int)0x8A15C00C);
24 | public const int WingetConfigErrorInvalidFieldValue = unchecked((int)0x8A15C00D);
25 | public const int WingetConfigErrorMissingField = unchecked((int)0x8A15C00E);
26 |
27 | // WinGet Configuration unit error codes:
28 | public const int WinGetConfigUnitNotFound = unchecked((int)0x8A15C101);
29 | public const int WinGetConfigUnitNotFoundRepository = unchecked((int)0x8A15C102);
30 | public const int WinGetConfigUnitMultipleMatches = unchecked((int)0x8A15C103);
31 | public const int WinGetConfigUnitInvokeGet = unchecked((int)0x8A15C104);
32 | public const int WinGetConfigUnitInvokeTest = unchecked((int)0x8A15C105);
33 | public const int WinGetConfigUnitInvokeSet = unchecked((int)0x8A15C106);
34 | public const int WinGetConfigUnitModuleConflict = unchecked((int)0x8A15C107);
35 | public const int WinGetConfigUnitImportModule = unchecked((int)0x8A15C108);
36 | public const int WinGetConfigUnitInvokeInvalidResult = unchecked((int)0x8A15C109);
37 | public const int WinGetConfigUnitSettingConfigRoot = unchecked((int)0x8A15C110);
38 | public const int WinGetConfigUnitImportModuleAdmin = unchecked((int)0x8A15C111);
39 | }
40 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/NativeMethods.txt:
--------------------------------------------------------------------------------
1 | CoCreateInstance
2 | CoMarshalInterface
3 | CoUnmarshalInterface
4 | CreateStreamOnHGlobal
5 | HRESULT_FROM_WIN32
6 | MSHCTX
7 | MSHLFLAGS
8 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/WindowsPackageManager Interop.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0-windows10.0.19041.0
5 | 10.0.19041.0
6 | 10.0.19041.0
7 | DevHome.SetupFlow.Common
8 | x86;x64;arm64
9 | win-x86;win-x64;win-arm64
10 | disable
11 |
12 |
13 |
17 |
18 | 10.0.19041.0
19 | Microsoft.Management.Deployment
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | all
32 | runtime; build; native; contentfiles; analyzers
33 |
34 |
35 |
46 |
47 | NU1701
48 | true
49 | none
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/WindowsPackageManager/ClassModel.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 |
7 | namespace WindowsPackageManager.Interop;
8 |
9 | internal sealed class ClassModel
10 | {
11 | ///
12 | /// Gets the interface for the projected class type generated by CsWinRT
13 | ///
14 | public Type InterfaceType { get; init; }
15 |
16 | ///
17 | /// Gets the projected class type generated by CsWinRT
18 | ///
19 | public Type ProjectedClassType { get; init; }
20 |
21 | ///
22 | /// Gets the clsids for each context (e.g. OutOfProcProd, OutOfProcDev)
23 | ///
24 | public IReadOnlyDictionary Clsids { get; init; }
25 |
26 | ///
27 | /// Get CLSID based on the provided context
28 | ///
29 | /// Context
30 | /// CLSID for the provided context.
31 | /// Throw an exception if the clsid context is not available for the current instance.
32 | public Guid GetClsid(ClsidContext context)
33 | {
34 | if (!Clsids.TryGetValue(context, out var clsid))
35 | {
36 | throw new InvalidOperationException($"{ProjectedClassType.FullName} is not implemented in context {context}");
37 | }
38 |
39 | return clsid;
40 | }
41 |
42 | ///
43 | /// Get IID corresponding to the COM object
44 | ///
45 | /// IID.
46 | public Guid GetIid()
47 | {
48 | return InterfaceType.GUID;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/WindowsPackageManager/ClassesDefinition.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using Microsoft.Management.Deployment;
7 |
8 | namespace WindowsPackageManager.Interop;
9 |
10 | internal static class ClassesDefinition
11 | {
12 | private static Dictionary Classes { get; } = new()
13 | {
14 | [typeof(PackageManager)] = new()
15 | {
16 | ProjectedClassType = typeof(PackageManager),
17 | InterfaceType = typeof(IPackageManager),
18 | Clsids = new Dictionary()
19 | {
20 | [ClsidContext.Prod] = new Guid("C53A4F16-787E-42A4-B304-29EFFB4BF597"),
21 | [ClsidContext.Dev] = new Guid("74CB3139-B7C5-4B9E-9388-E6616DEA288C"),
22 | },
23 | },
24 |
25 | [typeof(FindPackagesOptions)] = new()
26 | {
27 | ProjectedClassType = typeof(FindPackagesOptions),
28 | InterfaceType = typeof(IFindPackagesOptions),
29 | Clsids = new Dictionary()
30 | {
31 | [ClsidContext.Prod] = new Guid("572DED96-9C60-4526-8F92-EE7D91D38C1A"),
32 | [ClsidContext.Dev] = new Guid("1BD8FF3A-EC50-4F69-AEEE-DF4C9D3BAA96"),
33 | },
34 | },
35 |
36 | [typeof(CreateCompositePackageCatalogOptions)] = new()
37 | {
38 | ProjectedClassType = typeof(CreateCompositePackageCatalogOptions),
39 | InterfaceType = typeof(ICreateCompositePackageCatalogOptions),
40 | Clsids = new Dictionary()
41 | {
42 | [ClsidContext.Prod] = new Guid("526534B8-7E46-47C8-8416-B1685C327D37"),
43 | [ClsidContext.Dev] = new Guid("EE160901-B317-4EA7-9CC6-5355C6D7D8A7"),
44 | },
45 | },
46 |
47 | [typeof(InstallOptions)] = new()
48 | {
49 | ProjectedClassType = typeof(InstallOptions),
50 | InterfaceType = typeof(IInstallOptions),
51 | Clsids = new Dictionary()
52 | {
53 | [ClsidContext.Prod] = new Guid("1095F097-EB96-453B-B4E6-1613637F3B14"),
54 | [ClsidContext.Dev] = new Guid("44FE0580-62F7-44D4-9E91-AA9614AB3E86"),
55 | },
56 | },
57 |
58 | [typeof(UninstallOptions)] = new()
59 | {
60 | ProjectedClassType = typeof(UninstallOptions),
61 | InterfaceType = typeof(IUninstallOptions),
62 | Clsids = new Dictionary()
63 | {
64 | [ClsidContext.Prod] = new Guid("E1D9A11E-9F85-4D87-9C17-2B93143ADB8D"),
65 | [ClsidContext.Dev] = new Guid("AA2A5C04-1AD9-46C4-B74F-6B334AD7EB8C"),
66 | },
67 | },
68 |
69 | [typeof(PackageMatchFilter)] = new()
70 | {
71 | ProjectedClassType = typeof(PackageMatchFilter),
72 | InterfaceType = typeof(IPackageMatchFilter),
73 | Clsids = new Dictionary()
74 | {
75 | [ClsidContext.Prod] = new Guid("D02C9DAF-99DC-429C-B503-4E504E4AB000"),
76 | [ClsidContext.Dev] = new Guid("3F85B9F4-487A-4C48-9035-2903F8A6D9E8"),
77 | },
78 | },
79 | };
80 |
81 | ///
82 | /// Get CLSID based on the provided context for the specified type
83 | ///
84 | /// Projected class type
85 | /// Context
86 | /// CLSID for the provided context and type, or throw an exception if not found.
87 | /// Throws an exception if type is not a project class.
88 | public static Guid GetClsid(ClsidContext context)
89 | {
90 | ValidateType();
91 | return Classes[typeof(T)].GetClsid(context);
92 | }
93 |
94 | ///
95 | /// Get IID corresponding to the COM object
96 | ///
97 | /// Projected class type
98 | /// IID or throw an exception if not found.
99 | /// Throws an exception if type is not a project class.
100 | public static Guid GetIid()
101 | {
102 | ValidateType();
103 | return Classes[typeof(T)].GetIid();
104 | }
105 |
106 | ///
107 | /// Validate that the provided type is defined.
108 | ///
109 | /// Projected class type
110 | /// Throws an exception if type is not a project class.
111 | private static void ValidateType()
112 | {
113 | if (!Classes.ContainsKey(typeof(TType)))
114 | {
115 | throw new InvalidOperationException($"{typeof(TType).Name} is not a projected class type.");
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/WindowsPackageManager/ClsidContext.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace WindowsPackageManager.Interop;
5 |
6 | public enum ClsidContext
7 | {
8 | // Production CLSID Guids
9 | Prod,
10 |
11 | // Development CLSID Guids
12 | Dev,
13 | }
14 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/WindowsPackageManager/WindowsPackageManagerElevatedFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Runtime.InteropServices;
6 | using WinRT;
7 |
8 | namespace WindowsPackageManager.Interop;
9 |
10 | ///
11 | /// Factory for creating winget COM objects using manual activation
12 | /// to have them in an elevated context.
13 | ///
14 | ///
15 | /// This needs to be called from an elevated context, or the winget
16 | /// server will reject the connection.
17 | ///
18 | /// The WinGetServerManualActivation_CreateInstance function used here is defined in
19 | /// https://github.com/microsoft/winget-cli/blob/master/src/WinGetServer/WinGetServerManualActivation_Client.cpp
20 | ///
21 | /// This class is based on what the winget cmdlets do. See
22 | /// https://github.com/microsoft/winget-cli/blob/master/src/PowerShell/Microsoft.WinGet.Client/Helpers/ComObjectFactory.cs
23 | ///
24 | public class WindowsPackageManagerElevatedFactory : WindowsPackageManagerFactory
25 | {
26 | // The only CLSID context supported by the DLL we call is Prod.
27 | // If we want to use Dev classes we have to use a Dev version of the DLL.
28 | public WindowsPackageManagerElevatedFactory()
29 | : base(ClsidContext.Prod)
30 | {
31 | }
32 |
33 | protected override unsafe T CreateInstance(Guid clsid, Guid iid)
34 | {
35 | void* pUnknown = null;
36 |
37 | try
38 | {
39 | var hr = WinGetServerManualActivation_CreateInstance(in clsid, in iid, 0, out pUnknown);
40 | Marshal.ThrowExceptionForHR(hr);
41 | return MarshalInterface.FromAbi((IntPtr)pUnknown);
42 | }
43 | finally
44 | {
45 | // CoCreateInstance and FromAbi both AddRef on the native object.
46 | // Release once to prevent memory leak.
47 | if (pUnknown is not null)
48 | {
49 | Marshal.Release((IntPtr)pUnknown);
50 | }
51 | }
52 | }
53 |
54 | [DllImport("winrtact.dll", ExactSpelling = true)]
55 | private static unsafe extern int WinGetServerManualActivation_CreateInstance(
56 | in Guid clsid,
57 | in Guid iid,
58 | uint flags,
59 | out void* instance);
60 | }
61 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/WindowsPackageManager/WindowsPackageManagerFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using Microsoft.Management.Deployment;
6 |
7 | namespace WindowsPackageManager.Interop;
8 |
9 | ///
10 | /// Factory class for creating WinGet COM objects.
11 | /// Details about each method can be found in the source IDL:
12 | /// https://github.com/microsoft/winget-cli/blob/master/src/Microsoft.Management.Deployment/PackageManager.idl
13 | ///
14 | public abstract class WindowsPackageManagerFactory
15 | {
16 | private readonly ClsidContext _clsidContext;
17 |
18 | public WindowsPackageManagerFactory(ClsidContext clsidContext)
19 | {
20 | _clsidContext = clsidContext;
21 | }
22 |
23 | ///
24 | /// Creates an instance of the class .
25 | ///
26 | ///
27 | /// Type must be one of the types defined in the winget COM API.
28 | /// Implementations of this method can assume that and
29 | /// are the right GUIDs for the class in the given context.
30 | ///
31 | protected abstract T CreateInstance(Guid clsid, Guid iid);
32 |
33 | public PackageManager CreatePackageManager() => CreateInstance();
34 |
35 | public FindPackagesOptions CreateFindPackagesOptions() => CreateInstance();
36 |
37 | public CreateCompositePackageCatalogOptions CreateCreateCompositePackageCatalogOptions() => CreateInstance();
38 |
39 | public InstallOptions CreateInstallOptions() => CreateInstance();
40 |
41 | public UninstallOptions CreateUninstallOptions() => CreateInstance();
42 |
43 | public PackageMatchFilter CreatePackageMatchFilter() => CreateInstance();
44 |
45 | ///
46 | /// Creates an instance of the class .
47 | ///
48 | ///
49 | /// This is a helper for calling the derived class's
50 | /// method with the appropriate GUIDs.
51 | ///
52 | private T CreateInstance()
53 | {
54 | var clsid = ClassesDefinition.GetClsid(_clsidContext);
55 | var iid = ClassesDefinition.GetIid();
56 | return CreateInstance(clsid, iid);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/WindowsPackageManager Interop/WindowsPackageManager/WindowsPackageManagerStandardFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Runtime.InteropServices;
6 | using Windows.Win32;
7 | using Windows.Win32.System.Com;
8 | using WinRT;
9 |
10 | namespace WindowsPackageManager.Interop;
11 |
12 | public class WindowsPackageManagerStandardFactory : WindowsPackageManagerFactory
13 | {
14 | public WindowsPackageManagerStandardFactory(ClsidContext clsidContext = ClsidContext.Prod)
15 | : base(clsidContext)
16 | {
17 | }
18 |
19 | protected override T CreateInstance(Guid clsid, Guid iid)
20 | {
21 | var pUnknown = IntPtr.Zero;
22 | try
23 | {
24 | var hr = PInvoke.CoCreateInstance(clsid, null, CLSCTX.CLSCTX_ALL, iid, out var result);
25 | Marshal.ThrowExceptionForHR(hr);
26 | pUnknown = Marshal.GetIUnknownForObject(result);
27 | return MarshalGeneric.FromAbi(pUnknown);
28 | }
29 | finally
30 | {
31 | // CoCreateInstance and FromAbi both AddRef on the native object.
32 | // Release once to prevent memory leak.
33 | if (pUnknown != IntPtr.Zero)
34 | {
35 | Marshal.Release(pUnknown);
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------