Persisting custom properties on a Visual Studio project using object model

It is possible to persist custom properties in your Visual Studio project. I will show how using some PowerShell code in the NuGet console.

Note that VariableValue() persist in session, the call to VariablePersists() writes to the project file for persistance over sessions.

The Global object has the following methods:

PM> (Get-Project).Globals | gm    TypeName: System.__ComObject#{e68a3e0e-b435-4dde-86b7-f5adefc19df2}
 
Name             MemberType            Definition                                  ----             ----------            ----------                                  VariableExists   ParameterizedProperty bool VariableExists (string) {get}          VariablePersists ParameterizedProperty bool VariablePersists (string) {get} {set}  VariableValue    ParameterizedProperty Variant VariableValue (string) {get} {set}  DTE              Property              DTE DTE () {get}                            Parent           Property              IDispatch Parent () {get}                   VariableNames    Property              Variant VariableNames () {get}             

Some sample code:

PM> (Get-Project –name "MyProject").Globals.VariableValue("FirstProperty") = "Value1"
PM> (Get-Project –name "MyProject").Globals.VariableValue("SecondProperty") = "Value2"
PM> (Get-Project –name "MyProject").Globals.VariablePersists("FirstProperty") = $True   PM> (Get-Project –name "MyProject").Globals.VariablePersists("SecondProperty") = $True   PM> (Get-Project –name "MyProject").Globals.VariableValue("FirstProperty")
Value1
PM> (Get-Project –name "MyProject").Globals.VariablePersists("SecondProperty")
True
PM> (Get-Project –name "MyProject").Globals.VariableNames
FirstProperty
SecondProperty
PM> (Get-Project –name "MyProject").Globals.VariableExists("DoesNotExist")
False
PM> (Get-Project –name "MyProject").Globals.VariableExists("FirstProperty")
True

And if you look at your .csproj file:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  :
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />   <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets" />   <ProjectExtensions>     <VisualStudio>       <UserProperties SecondProperty="Value2" FirstProperty="Value1" />
    </VisualStudio>   </ProjectExtensions>
</Project>

3 Comments

Comments have been disabled for this content.