다음을 통해 공유


방법: SharePoint 프로젝트에 속성 추가

프로젝트 확장을 사용하여 SharePoint 프로젝트에 속성을 추가할 수 있습니다. 솔루션 탐색기에서 프로젝트를 선택하면 속성 창에 해당 속성이 표시됩니다.

다음 단계에서는 프로젝트 확장이 이미 만들어져 있는 것으로 가정합니다. 자세한 내용은 방법: SharePoint 프로젝트 확장 만들기를 참조하십시오.

SharePoint 프로젝트에 속성을 추가하려면

  1. SharePoint 프로젝트에 추가할 속성을 나타내는 공용 속성이 있는 클래스를 정의합니다. 여러 속성을 추가하려는 경우 모든 속성을 동일한 클래스 또는 서로 다른 여러 클래스에 정의할 수 있습니다.

  2. ISharePointProjectExtension 구현의 Initialize 메서드에서 projectService 매개 변수의 ProjectPropertiesRequested 이벤트를 처리합니다.

  3. ProjectPropertiesRequested 이벤트의 이벤트 처리기에서 속성 클래스의 인스턴스를 이벤트 인수 매개 변수의 PropertySources 컬렉션에 추가합니다.

예제

다음 코드 예제에서는 SharePoint 프로젝트에 두 가지 속성을 추가하는 방법을 보여 줍니다. 한 속성은 프로젝트 사용자 옵션 파일(.csproj.user 파일 또는 .vbproj.user 파일)에 데이터를 유지하고, 다른 속성은 프로젝트 파일(.csproj 파일 또는 .vbproj 파일)에 데이터를 유지합니다.

Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Composition
Imports Microsoft.VisualStudio
Imports Microsoft.VisualStudio.SharePoint
Imports Microsoft.VisualStudio.Shell.Interop

Namespace CustomSharePointProperty

    <Export(GetType(ISharePointProjectExtension))> _
    Partial Friend Class ProjectExtensionWithProperty
        Implements ISharePointProjectExtension

        Public Sub Initialize(ByVal projectService As ISharePointProjectService) _
            Implements ISharePointProjectExtension.Initialize
            AddHandler projectService.ProjectPropertiesRequested, _
                AddressOf ProjectPropertiesRequested
        End Sub

        Private Sub ProjectPropertiesRequested(ByVal sender As Object, _
            ByVal e As SharePointProjectPropertiesRequestedEventArgs)

            Dim propertiesObject As CustomProjectProperties = Nothing

            ' If the properties object already exists, get it from the project's annotations.
            If False = e.Project.Annotations.TryGetValue(propertiesObject) Then
                ' Otherwise, create a new properties object and add it to the annotations.
                propertiesObject = New CustomProjectProperties(e.Project)
                e.Project.Annotations.Add(propertiesObject)
            End If

            e.PropertySources.Add(propertiesObject)
        End Sub
    End Class

    Public Class CustomProjectProperties
        Private sharePointProject As ISharePointProject
        Private projectStorage As IVsBuildPropertyStorage
        Private Const ProjectFilePropertyId As String = "ContosoCustomProjectFileProperty"
        Private Const ProjectFilePropertyDefaultValue As String = "Default"

        Public Sub New(ByVal myProject As ISharePointProject)
            sharePointProject = myProject
            projectStorage = sharePointProject.ProjectService.Convert(Of ISharePointProject, IVsBuildPropertyStorage)(sharePointProject)
        End Sub

        <DisplayName("Custom Project File Property")> _
        <DescriptionAttribute("This property is saved to the .csproj/.vbproj file.")> _
        <DefaultValue(ProjectFilePropertyDefaultValue)> _
        Public Property CustomProjectFileProperty As String
            Get
                Dim propertyValue As String = String.Empty
                Dim hr As Integer = projectStorage.GetPropertyValue(ProjectFilePropertyId, String.Empty, _
                    CUInt(_PersistStorageType.PST_PROJECT_FILE), propertyValue)

                ' Try to get the current value from the project file; if it does not yet exist, return a default value.
                If Not ErrorHandler.Succeeded(hr) Or String.IsNullOrEmpty(propertyValue) Then
                    propertyValue = ProjectFilePropertyDefaultValue
                End If
                Return propertyValue
            End Get
            Set(ByVal value As String)
                ' Do not save the default value.
                If value <> ProjectFilePropertyDefaultValue Then
                    projectStorage.SetPropertyValue(ProjectFilePropertyId, String.Empty, _
                        CUInt(_PersistStorageType.PST_PROJECT_FILE), value)
                End If
            End Set
        End Property

        Private Const UserFilePropertyId As String = "ContosoCustomUserFileProperty"
        Private Const UserFilePropertyDefaultValue As String = "Default"

        <DisplayName("Custom Project User File Property")> _
        <DescriptionAttribute("This property is saved to the .user file.")> _
        <DefaultValue(UserFilePropertyDefaultValue)> _
        Public Property CustomUserFileProperty As String
            Get
                Dim propertyValue As String = String.Empty
                ' Try to get the current value from the .user file; if it does not yet exist, return a default value.
                If Not sharePointProject.ProjectUserFileData.TryGetValue(UserFilePropertyId, propertyValue) Then
                    propertyValue = UserFilePropertyDefaultValue
                End If
                Return propertyValue
            End Get
            Set(ByVal value As String)
                ' Do not save the default value.
                If value <> UserFilePropertyDefaultValue Then
                    sharePointProject.ProjectUserFileData(UserFilePropertyId) = value
                End If
            End Set
        End Property
    End Class
End Namespace
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.Shell.Interop;

namespace CustomSharePointProperty
{
    [Export(typeof(ISharePointProjectExtension))]
    public class ProjectExtensionWithProperty : ISharePointProjectExtension
    {
        public void Initialize(ISharePointProjectService projectService)
        {
            projectService.ProjectPropertiesRequested += projectService_ProjectPropertiesRequested;           
        }

        void projectService_ProjectPropertiesRequested(object sender, SharePointProjectPropertiesRequestedEventArgs e)
        {
            CustomProjectProperties propertiesObject;

            // If the properties object already exists, get it from the project's annotations.
            if (!e.Project.Annotations.TryGetValue(out propertiesObject))
            {
                // Otherwise, create a new properties object and add it to the annotations.
                propertiesObject = new CustomProjectProperties(e.Project);
                e.Project.Annotations.Add(propertiesObject);
            }

            e.PropertySources.Add(propertiesObject);
        }
    }

    public class CustomProjectProperties
    {
        private ISharePointProject sharePointProject;
        private IVsBuildPropertyStorage projectStorage;
        private const string ProjectFilePropertyId = "ContosoCustomProjectFileProperty";
        private const string ProjectFilePropertyDefaultValue = "Default";

        public CustomProjectProperties(ISharePointProject myProject)
        {
            sharePointProject = myProject;
            projectStorage = sharePointProject.ProjectService.Convert<ISharePointProject, IVsBuildPropertyStorage>(sharePointProject);
        }

        [DisplayName("Custom Project File Property")]
        [DescriptionAttribute("This property is saved to the .csproj/.vbproj file.")]
        [DefaultValue(ProjectFilePropertyDefaultValue)]
        public string CustomProjectFileProperty
        {
            get
            {
                string propertyValue;
                int hr = projectStorage.GetPropertyValue(ProjectFilePropertyId, string.Empty, 
                    (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue);

                // Try to get the current value from the project file; if it does not yet exist, return a default value.
                if (!ErrorHandler.Succeeded(hr) || String.IsNullOrEmpty(propertyValue))
                {
                    propertyValue = ProjectFilePropertyDefaultValue;
                }

                return propertyValue;
            }

            set
            {
                // Do not save the default value.
                if (value != ProjectFilePropertyDefaultValue)
                {
                    projectStorage.SetPropertyValue(ProjectFilePropertyId, string.Empty, 
                        (uint)_PersistStorageType.PST_PROJECT_FILE, value);
                }
            }
        }

        private const string UserFilePropertyId = "ContosoCustomUserFileProperty";
        private const string UserFilePropertyDefaultValue = "Default";

        [DisplayName("Custom Project User File Property")]
        [DescriptionAttribute("This property is saved to the .user file.")]
        [DefaultValue(UserFilePropertyDefaultValue)]
        public string CustomUserFileProperty
        {
            get
            {
                string propertyValue = string.Empty;

                // Try to get the current value from the .user file; if it does not yet exist, return a default value.
                if (!sharePointProject.ProjectUserFileData.TryGetValue(UserFilePropertyId, out propertyValue))
                {
                    propertyValue = UserFilePropertyDefaultValue; 
                }

                return propertyValue; 
            }

            set
            {
                // Do not save the default value.
                if (value != UserFilePropertyDefaultValue)
                {
                    sharePointProject.ProjectUserFileData[UserFilePropertyId] = value;
                }
            }
        }                
    }
}

코드 이해

ProjectPropertiesRequested 이벤트가 발생할 때마다 CustomProjectProperties 클래스의 동일한 인스턴스가 사용되도록 하기 위해 다음 코드 예제에서는 이 이벤트가 처음 발생하는 시점에 프로젝트의 Annotations 속성에 속성 개체를 추가합니다. 이 코드에서는 이 이벤트가 다시 발생할 때마다 이 개체를 검색합니다. Annotations 속성을 사용하여 프로젝트에 데이터를 연결하는 방법에 대한 자세한 내용은 SharePoint 도구 확장과 사용자 지정 데이터 연결을 참조하십시오.

속성 값의 변경 내용을 유지하기 위해 속성에 대한 set 접근자는 다음 API를 사용합니다.

이러한 파일에 데이터를 유지하는 방법에 대한 자세한 내용은 SharePoint 프로젝트 시스템의 확장에 데이터 저장을 참조하십시오.

사용자 지정 속성의 동작 지정

System.ComponentModel 네임스페이스의 특성을 속성 정의에 적용하여 사용자 지정 속성이 속성 창에서 표시되고 동작하는 방식을 정의할 수 있습니다. 다음 특성은 여러 시나리오에서 유용합니다.

  • DisplayNameAttribute. 속성 창에 표시되는 속성의 이름을 지정합니다.

  • DescriptionAttribute. 속성을 선택할 때 속성 창의 아래쪽에 나타나는 설명 문자열을 지정합니다.

  • DefaultValueAttribute. 속성의 기본값을 지정합니다.

  • TypeConverterAttribute. 속성 창에 나타나는 문자열과 문자열 이외의 속성 값 사이의 사용자 지정 변환을 지정합니다.

  • EditorAttribute. 속성을 수정하는 데 사용할 사용자 지정 편집기를 지정합니다.

코드 컴파일

이 예제에는 다음 어셈블리에 대한 참조가 필요합니다.

  • Microsoft.VisualStudio.SharePoint

  • Microsoft.VisualStudio.Shell

  • Microsoft.VisualStudio.Shell.Interop

  • Microsoft.VisualStudio.Shell.Interop.8.0

  • System.ComponentModel.Composition

확장 배포

확장을 배포하려면 어셈블리 및 확장과 함께 배포할 다른 모든 파일에 대한 VSIX(Visual Studio Extension) 패키지를 만듭니다. 자세한 내용은 Visual Studio에서 SharePoint 도구에 대한 확장 배포를 참조하십시오.

참고 항목

작업

방법: SharePoint 프로젝트 확장 만들기

개념

SharePoint 프로젝트 시스템 확장

기타 리소스

SharePoint 프로젝트 확장

방법: SharePoint 프로젝트에 바로 가기 메뉴 항목 추가