IDataSource 인터페이스

정의

데이터 바인딩된 컨트롤을 바인딩할 추상 데이터 소스를 나타냅니다.

public interface class IDataSource
public interface IDataSource
type IDataSource = interface
Public Interface IDataSource
파생

예제

다음 코드 예제에서는 클래스를 정의 하는 메서드의 구현 방법을 보여 줍니다는 IDataSource 데이터 바인딩된 컨트롤에 데이터를 제공 하는 인터페이스입니다. 이 예제의 데이터 소스 컨트롤 쉼표로 구분 된 값 파일에서 데이터 소스 역할을 하 고 쉼표로 구분 된 파일 데이터를 표시할 모든 데이터 바인딩된 컨트롤에서 사용할 수 있습니다. 이 코드 예제는에 대해 제공 된 큰 예제의 일부는 DataSourceControl 클래스입니다.

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

// The CsvDataSource is a data source control that retrieves its
// data from a comma-separated value file.
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Minimal)]
public class CsvDataSource : DataSourceControl
{
    public CsvDataSource() : base() {}

    // The comma-separated value file to retrieve data from.
    public string FileName {
        get {
            return ((CsvDataSourceView)this.GetView(String.Empty)).SourceFile;
        }
        set {
            // Only set if it is different.
            if ( ((CsvDataSourceView)this.GetView(String.Empty)).SourceFile != value) {
                ((CsvDataSourceView)this.GetView(String.Empty)).SourceFile = value;
                RaiseDataSourceChangedEvent(EventArgs.Empty);
            }
        }
    }

    // Do not add the column names as a data row. Infer columns if the CSV file does
    // not include column names.
    public bool IncludesColumnNames {
        get {
            return ((CsvDataSourceView)this.GetView(String.Empty)).IncludesColumnNames;
        }
        set {
            // Only set if it is different.
            if ( ((CsvDataSourceView)this.GetView(String.Empty)).IncludesColumnNames != value) {
                ((CsvDataSourceView)this.GetView(String.Empty)).IncludesColumnNames = value;
                RaiseDataSourceChangedEvent(EventArgs.Empty);
            }
        }
    }

    // Return a strongly typed view for the current data source control.
    private CsvDataSourceView view = null;
    protected override DataSourceView GetView(string viewName) {
        if (null == view) {
            view = new CsvDataSourceView(this, String.Empty);
        }
        return view;
    }
    // The ListSourceHelper class calls GetList, which
    // calls the DataSourceControl.GetViewNames method.
    // Override the original implementation to return
    // a collection of one element, the default view name.
    protected override ICollection GetViewNames() {
        ArrayList al = new ArrayList(1);
        al.Add(CsvDataSourceView.DefaultViewName);
        return al as ICollection;
    }
}

// The CsvDataSourceView class encapsulates the
// capabilities of the CsvDataSource data source control.
public class CsvDataSourceView : DataSourceView
{

    public CsvDataSourceView(IDataSource owner, string name) :base(owner, DefaultViewName) {
    }

    // The data source view is named. However, the CsvDataSource
    // only supports one view, so the name is ignored, and the
    // default name used instead.
    public static string DefaultViewName = "CommaSeparatedView";

    // The location of the .csv file.
    private string sourceFile = String.Empty;
    internal string SourceFile {
        get {
            return sourceFile;
        }
        set {
            // Use MapPath when the SourceFile is set, so that files local to the
            // current directory can be easily used.
            string mappedFileName = HttpContext.Current.Server.MapPath(value);
            sourceFile = mappedFileName;
        }
    }

    // Do not add the column names as a data row. Infer columns if the CSV file does
    // not include column names.
    private bool columns = false;
    internal bool IncludesColumnNames {
        get {
            return columns;
        }
        set {
            columns = value;
        }
    }

    // Get data from the underlying data source.
    // Build and return a DataView, regardless of mode.
    protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs) {
        IEnumerable dataList = null;
        // Open the .csv file.
        if (File.Exists(this.SourceFile)) {
            DataTable data = new DataTable();

            // Open the file to read from.
            using (StreamReader sr = File.OpenText(this.SourceFile)) {
                // Parse the line
                string s = "";
                string[] dataValues;
                DataColumn col;

                // Do the following to add schema.
                dataValues = sr.ReadLine().Split(',');
                // For each token in the comma-delimited string, add a column
                // to the DataTable schema.
                foreach (string token in dataValues) {
                    col = new DataColumn(token,typeof(string));
                    data.Columns.Add(col);
                }

                // Do not add the first row as data if the CSV file includes column names.
                if (! IncludesColumnNames)
                    data.Rows.Add(CopyRowData(dataValues, data.NewRow()));

                // Do the following to add data.
                while ((s = sr.ReadLine()) != null) {
                    dataValues = s.Split(',');
                    data.Rows.Add(CopyRowData(dataValues, data.NewRow()));
                }
            }
            data.AcceptChanges();
            DataView dataView = new DataView(data);
            if (!string.IsNullOrEmpty(selectArgs.SortExpression)) {
                dataView.Sort = selectArgs.SortExpression;
            }
            dataList = dataView;
        }
        else {
            throw new System.Configuration.ConfigurationErrorsException("File not found, " + this.SourceFile);
        }

        if (null == dataList) {
            throw new InvalidOperationException("No data loaded from data source.");
        }

        return dataList;
    }

    private DataRow CopyRowData(string[] source, DataRow target) {
        try {
            for (int i = 0;i < source.Length;i++) {
                target[i] = source[i];
            }
        }
        catch (System.IndexOutOfRangeException) {
            // There are more columns in this row than
            // the original schema allows.  Stop copying
            // and return the DataRow.
            return target;
        }
        return target;
    }
    // The CsvDataSourceView does not currently
    // permit deletion. You can modify or extend
    // this sample to do so.
    public override bool CanDelete {
        get {
            return false;
        }
    }
    protected override int ExecuteDelete(IDictionary keys, IDictionary values)
    {
        throw new NotSupportedException();
    }
    // The CsvDataSourceView does not currently
    // permit insertion of a new record. You can
    // modify or extend this sample to do so.
    public override bool CanInsert {
        get {
            return false;
        }
    }
    protected override int ExecuteInsert(IDictionary values)
    {
        throw new NotSupportedException();
    }
    // The CsvDataSourceView does not currently
    // permit update operations. You can modify or
    // extend this sample to do so.
    public override bool CanUpdate {
        get {
            return false;
        }
    }
    protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)
    {
        throw new NotSupportedException();
    }
}
Imports System.Collections
Imports System.Data
Imports System.IO
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet.VB.Controls

' The CsvDataSource is a data source control that retrieves its
' data from a comma-separated value file.
<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class CsvDataSource
   Inherits DataSourceControl

   Public Sub New()
   End Sub

   ' The comma-separated value file to retrieve data from.
   Public Property FileName() As String
      Get
         Return CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile
      End Get
      Set
         ' Only set if it is different.
         If CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile <> value Then
            CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile = value
            RaiseDataSourceChangedEvent(EventArgs.Empty)
         End If
      End Set
   End Property

   ' Do not add the column names as a data row. Infer columns if the CSV file does
   ' not include column names.

   Public Property IncludesColumnNames() As Boolean
      Get
         Return CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames
      End Get
      Set
         ' Only set if it is different.
         If CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames <> value Then
            CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames = value
            RaiseDataSourceChangedEvent(EventArgs.Empty)
         End If
      End Set
   End Property


   ' Return a strongly typed view for the current data source control.
   Private view As CsvDataSourceView = Nothing

   Protected Overrides Function GetView(viewName As String) As DataSourceView
      If view Is Nothing Then
         view = New CsvDataSourceView(Me, String.Empty)
      End If
      Return view
   End Function 'GetView

   ' The ListSourceHelper class calls GetList, which
   ' calls the DataSourceControl.GetViewNames method.
   ' Override the original implementation to return
   ' a collection of one element, the default view name.
   Protected Overrides Function GetViewNames() As ICollection
      Dim al As New ArrayList(1)
      al.Add(CsvDataSourceView.DefaultViewName)
      Return CType(al, ICollection)
   End Function 'GetViewNames

End Class


' The CsvDataSourceView class encapsulates the
' capabilities of the CsvDataSource data source control.

Public Class CsvDataSourceView
   Inherits DataSourceView

   Public Sub New(owner As IDataSource, name As String)
       MyBase.New(owner, DefaultViewName)
   End Sub

   ' The data source view is named. However, the CsvDataSource
   ' only supports one view, so the name is ignored, and the
   ' default name used instead.
   Public Shared DefaultViewName As String = "CommaSeparatedView"

   ' The location of the .csv file.
   Private aSourceFile As String = [String].Empty

   Friend Property SourceFile() As String
      Get
         Return aSourceFile
      End Get
      Set
         ' Use MapPath when the SourceFile is set, so that files local to the
         ' current directory can be easily used.
         Dim mappedFileName As String
         mappedFileName = HttpContext.Current.Server.MapPath(value)
         aSourceFile = mappedFileName
      End Set
   End Property

   ' Do not add the column names as a data row. Infer columns if the CSV file does
   ' not include column names.
   Private columns As Boolean = False

   Friend Property IncludesColumnNames() As Boolean
      Get
         Return columns
      End Get
      Set
         columns = value
      End Set
   End Property

   ' Get data from the underlying data source.
   ' Build and return a DataView, regardless of mode.
   Protected Overrides Function ExecuteSelect(selectArgs As DataSourceSelectArguments) _
    As System.Collections.IEnumerable
      Dim dataList As IEnumerable = Nothing
      ' Open the .csv file.
      If File.Exists(Me.SourceFile) Then
         Dim data As New DataTable()

         ' Open the file to read from.
         Dim sr As StreamReader = File.OpenText(Me.SourceFile)

         Try
            ' Parse the line
            Dim dataValues() As String
            Dim col As DataColumn

            ' Do the following to add schema.
            dataValues = sr.ReadLine().Split(","c)
            ' For each token in the comma-delimited string, add a column
            ' to the DataTable schema.
            Dim token As String
            For Each token In dataValues
               col = New DataColumn(token, System.Type.GetType("System.String"))
               data.Columns.Add(col)
            Next token

            ' Do not add the first row as data if the CSV file includes column names.
            If Not IncludesColumnNames Then
               data.Rows.Add(CopyRowData(dataValues, data.NewRow()))
            End If

            ' Do the following to add data.
            Dim s As String
            Do
               s = sr.ReadLine()
               If Not s Is Nothing Then
                   dataValues = s.Split(","c)
                   data.Rows.Add(CopyRowData(dataValues, data.NewRow()))
               End If
            Loop Until s Is Nothing

         Finally
            sr.Close()
         End Try

         data.AcceptChanges()
         Dim dataView As New DataView(data)
         If Not selectArgs.SortExpression Is String.Empty Then
             dataView.Sort = selectArgs.SortExpression
         End If
         dataList = dataView
      Else
         Throw New System.Configuration.ConfigurationErrorsException("File not found, " + Me.SourceFile)
      End If

      If dataList is Nothing Then
         Throw New InvalidOperationException("No data loaded from data source.")
      End If

      Return dataList
   End Function 'ExecuteSelect


   Private Function CopyRowData([source]() As String, target As DataRow) As DataRow
      Try
         Dim i As Integer
         For i = 0 To [source].Length - 1
            target(i) = [source](i)
         Next i
      Catch iore As IndexOutOfRangeException
         ' There are more columns in this row than
         ' the original schema allows.  Stop copying
         ' and return the DataRow.
         Return target
      End Try
      Return target
   End Function 'CopyRowData

   ' The CsvDataSourceView does not currently
   ' permit deletion. You can modify or extend
   ' this sample to do so.
   Public Overrides ReadOnly Property CanDelete() As Boolean
      Get
         Return False
      End Get
   End Property

   Protected Overrides Function ExecuteDelete(keys As IDictionary, values As IDictionary) As Integer
      Throw New NotSupportedException()
   End Function 'ExecuteDelete

   ' The CsvDataSourceView does not currently
   ' permit insertion of a new record. You can
   ' modify or extend this sample to do so.
   Public Overrides ReadOnly Property CanInsert() As Boolean
      Get
         Return False
      End Get
   End Property

   Protected Overrides Function ExecuteInsert(values As IDictionary) As Integer
      Throw New NotSupportedException()
   End Function 'ExecuteInsert

   ' The CsvDataSourceView does not currently
   ' permit update operations. You can modify or
   ' extend this sample to do so.
   Public Overrides ReadOnly Property CanUpdate() As Boolean
      Get
         Return False
      End Get
   End Property

   Protected Overrides Function ExecuteUpdate(keys As IDictionary, _
                                              values As IDictionary, _
                                              oldValues As IDictionary) As Integer
      Throw New NotSupportedException()
   End Function 'ExecuteUpdate

End Class
End Namespace

설명

ASP.NET 웹 서버 컨트롤에 일관 된 방식으로 데이터를 바인딩할 수 있게 해 주는 컨트롤 데이터 바인딩 아키텍처를 지원 합니다. 데이터에 바인딩되는 웹 서버 컨트롤은 데이터 바인딩된 컨트롤과 바인딩 데이터 소스 컨트롤 이라고 하는 클래스 라고 합니다. 데이터 소스 컨트롤에서 모든 데이터 소스를 나타낼 수 있습니다: 관계형 데이터베이스, 파일, 스트림, 비즈니스 개체 및 등입니다. 데이터 소스 컨트롤에서 소스 나 기본 데이터의 형식에 관계 없이 데이터 바인딩된 컨트롤에 일관 된 방식으로 데이터를 제공 합니다.

구현 하는 IDataSource 사용자 고유의 사용자 지정 ASP.NET 데이터 소스 제어를 구현 하려는 경우 인터페이스.

구현 하는 클래스는 IDataSource 인터페이스는 데이터 소스 컨트롤입니다. 합니다 IDataSource 인터페이스는 모든 ASP.NET 데이터 원본에 대 한 기초를 제어 하 고 해당 두 가지 방법으로 기본 데이터 바인딩 아키텍처 개념 중 하나를 정의: 합니다 GetView 메서드 및 GetViewNames 메서드. 이 개념은 모든 데이터 소스 컨트롤은 해당 데이터에 대해 하나 이상의 명명 된 뷰를 지원 합니다. 데이터 원본 뷰 개체는 비슷합니다는 DataView 추상화를 System.Data 네임 스페이스:를 데이터 바인딩 가능, 정렬, 필터링 및 뷰를 정의 하는 다른 데이터 작업에 대 한 데이터의 뷰 사용자 지정 합니다. 본질적으로 데이터 원본을 아무 작업도 수행 하지 제어 보다 보기 데이터를 검색 합니다.

데이터 소스 컨트롤에는 하나 이상의 연결 된 데이터 원본 뷰 개체 있을 수 있습니다. 일부 데이터 소스와 같은 관계형 데이터베이스를 표시 하는 것을 비롯 하 여 컨트롤 SqlDataSourceAccessDataSource, 보기가 하나만 지원 합니다. 다른 데이터 소스와 같은 계층적 데이터 소스 컨트롤을 비롯 하 여 컨트롤 SiteMapDataSource, 여러 뷰를 지원 합니다. 데이터 원본 뷰의 데이터 원본 및 지원 되는 작업의 기능을 정의 합니다.

요약 하자면, 데이터 소스 컨트롤 구현를 IDataSource 인터페이스, 하나를 지원 또는 이상의 명명 된 뷰 데이터 고, 항상 나타내는 데이터 원본에서 데이터 검색을 지원 합니다. 데이터 소스 컨트롤은 항상 경우와 같이 필요에 따라 데이터를 검색 DataBind 데이터 바인딩된 컨트롤에서 호출 됩니다.

메서드

GetView(String)

데이터 소스 컨트롤이 연결된 명명된 데이터 소스 뷰를 가져옵니다.

GetViewNames()

IDataSource 인터페이스와 관련된 뷰 개체의 목록을 나타내는 이름의 컬렉션을 가져옵니다.

이벤트

DataSourceChanged

데이터 바인딩된 컨트롤에 영향을 주는 방식으로 데이터 소스 컨트롤이 변경된 경우에 발생합니다.

확장 메서드

GetDefaultValues(IDataSource)

지정된 데이터 소스의 기본값에 대한 컬렉션을 가져옵니다.

GetMetaTable(IDataSource)

지정된 데이터 소스 개체의 테이블에 대한 메타데이터를 가져옵니다.

TryGetMetaTable(IDataSource, MetaTable)

테이블 메타데이터를 사용할 수 있는지 여부를 결정합니다.

적용 대상

추가 정보