HierarchicalDataSourceControl Class
This page is specific to:.NET Framework Version:2.03.03.54.0
HierarchicalDataSourceControl Class
Provides a base class for data source controls that represent hierarchical data.

Namespace: System.Web.UI
Assembly: System.Web (in system.web.dll)

Syntax

'Usage

Dim instance As HierarchicalDataSourceControl


'Declaration

<BindableAttribute(False)> _
Public MustInherit Class HierarchicalDataSourceControl
    Inherits Control
    Implements IHierarchicalDataSource
/** @attribute BindableAttribute(false) */ 
public abstract class HierarchicalDataSourceControl extends Control implements IHierarchicalDataSource
Not applicable.
Remarks

ASP.NET supports a controls data-binding architecture that enables Web server controls to bind to data and present it in a consistent fashion. Web server controls that bind to data are called data-bound controls, and the classes that facilitate binding are called data source controls. Data source controls can represent any data source: a file, a stream, a relational database, a business object, and so on. Data source controls present data in a consistent way to data-bound controls, regardless of the source or format of the underlying data.

Data source controls that represent hierarchical data derive from the HierarchicalDataSourceControl class, while data source controls that represent lists or tables of data derive from the DataSourceControl class. The HierarchicalDataSourceControl class is the base implementation of the IHierarchicalDataSource interface, which defines a single method to retrieve hierarchical data source view objects associated with the data source control, GetHierarchicalView.

You can think of a data source control as the combination of the HierarchicalDataSourceControl object and its associated views on the underlying data, called data source view objects. While data source controls that represent tabular data are typically associated with only one named view, the HierarchicalDataSourceControl class supports a data source view for each level of hierarchical data that the data source control represents. The level of hierarchical data is identified by a unique hierarchical path, passed to the GetHierarchicalView method in the viewPath parameter. Each HierarchicalDataSourceView object defines the capabilities of a data source control for the hierarchical level represented, and performs operations such as insert, update, delete, and sort.

Web server controls that derive from the HierarchicalDataBoundControl class, such as TreeView, use hierarchical data source controls to bind to hierarchical data.

Data source controls are implemented as controls to enable declarative persistence and to optionally permit participation in state management. Data source controls have no visual rendering, and therefore do not support themes.

Example

The following code example demonstrates how to extend the abstract HierarchicalDataSourceControl class and the HierarchicalDataSourceView class, and implement the IHierarchicalEnumerable and IHierarchyData interfaces to create a hierarchical data source control that retrieves file system information. The FileSystemDataSource control enables Web server controls to bind to FileSystemInfo objects and display basic file system information. The FileSystemDataSource class in the example provides the implementation of the GetHierarchicalView method, which retrieves a FileSystemDataSourceView object. The FileSystemDataSourceView object retrieves the data from the underlying data storage, in this case the file system information on the Web server. For security purposes, file system information is displayed only if the data source control is being used in a localhost, authenticated scenario, and only starts with the virtual directory that the Web Forms page using the data source control resides in. Finally, two classes that implement IHierarchicalEnumerable and IHierarchyData are provided to wrap the FileSystemInfo objects that FileSystemDataSource uses.

Imports System
Imports System.Collections
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet

<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class FileSystemDataSource
   Inherits HierarchicalDataSourceControl

   Public Sub New()
   End Sub 'New
   ' Return a strongly typed view for the current data source control.
   Private view As FileSystemDataSourceView = Nothing

   Protected Overrides Function GetHierarchicalView(viewPath As String) As HierarchicalDataSourceView
      If view Is Nothing Then
         view = New FileSystemDataSourceView(viewPath)
      End If
      Return view
   End Function 'GetHierarchicalView

End Class 'FileSystemDataSource
' The FileSystemDataSourceView class encapsulates the
' capabilities of the FileSystemDataSource data source control.

Public Class FileSystemDataSourceView
   Inherits HierarchicalDataSourceView

   Private _viewPath As String

   Public Sub New(viewPath As String)
       ' This implementation of HierarchicalDataSourceView does not
       ' use the viewPath parameter but other implementations
       ' could make use of it for retrieving values.
       _viewPath = viewPath
   End Sub 'New


   ' Starting with the rootNode, recursively build a list of
   ' FileSystemInfo nodes, create FileSystemHierarchyData
   ' objects, add them all to the FileSystemHierarchicalEnumerable,
   ' and return the list.
   Public Overrides Function [Select]() As IHierarchicalEnumerable
      Dim currentRequest As HttpRequest = HttpContext.Current.Request

      ' SECURITY: There are many security issues that can be raised
      ' SECURITY: by exposing the file system structure of a Web server
      ' SECURITY: to an anonymous user in a limited trust scenario such as
      ' SECURITY: a Web page served on an intranet or the Internet.
      ' SECURITY: For this reason, the FileSystemDataSource only
      ' SECURITY: shows data when the HttpRequest is received
      ' SECURITY: from a local Web server. In addition, the data source
      ' SECURITY: does not display data to anonymous users.
      If currentRequest.IsAuthenticated AndAlso(currentRequest.UserHostAddress = "127.0.0.1" OrElse currentRequest.UserHostAddress = "::1") Then

         ' The ApplicationPath returns a physical path in VB, so do not MapPath.
         Dim rootPath As String = currentRequest.MapPath(currentRequest.ApplicationPath)

         Dim rootDirectory As New DirectoryInfo(rootPath)

         Dim fshe As New FileSystemHierarchicalEnumerable()

         Dim fsi As FileSystemInfo
         For Each fsi In  rootDirectory.GetFileSystemInfos()
            fshe.Add(New FileSystemHierarchyData(fsi))
         Next fsi
         Return fshe
      Else
         Throw New NotSupportedException("The FileSystemDataSource only " + "presents data in an authenticated, localhost context.")
      End If
   End Function 'Select
End Class 'FileSystemDataSourceView
' A collection of FileSystemHierarchyData objects

Public Class FileSystemHierarchicalEnumerable
   Inherits ArrayList
   Implements IHierarchicalEnumerable

   Public Sub New()
   End Sub 'New


   Public Overridable Function GetHierarchyData(enumeratedItem As Object) As IHierarchyData _
    Implements IHierarchicalEnumerable.GetHierarchyData
      Return CType(enumeratedItem, IHierarchyData)
   End Function 'GetHierarchyData

End Class 'FileSystemHierarchicalEnumerable


Public Class FileSystemHierarchyData
   Implements IHierarchyData

   Public Sub New(obj As FileSystemInfo)
      fileSystemObject = obj
   End Sub 'New

   Private fileSystemObject As FileSystemInfo = Nothing

   Public Overrides Function ToString() As String
      Return fileSystemObject.Name
   End Function 'ToString

   ' IHierarchyData implementation.
   Public Overridable ReadOnly Property HasChildren() As Boolean _
    Implements IHierarchyData.HasChildren
      Get
         If GetType(DirectoryInfo) Is fileSystemObject.GetType() Then
            Dim temp As DirectoryInfo = CType(fileSystemObject, DirectoryInfo)
            Return temp.GetFileSystemInfos().Length > 0
         Else
            Return False
         End If
      End Get
   End Property
   ' DirectoryInfo returns the OriginalPath, while FileInfo returns
   ' a fully qualified path.

   Public Overridable ReadOnly Property Path() As String _
    Implements IHierarchyData.Path
      Get
         Return fileSystemObject.ToString()
      End Get
   End Property

   Public Overridable ReadOnly Property Item() As Object _
    Implements IHierarchyData.Item
      Get
         Return fileSystemObject
      End Get
   End Property

   Public Overridable ReadOnly Property Type() As String _
    Implements IHierarchyData.Type
      Get
         Return "FileSystemData"
      End Get
   End Property

   Public Overridable Function GetChildren() As IHierarchicalEnumerable _
    Implements IHierarchyData.GetChildren
      Dim children As New FileSystemHierarchicalEnumerable()

      If GetType(DirectoryInfo) Is fileSystemObject.GetType() Then
         Dim temp As DirectoryInfo = CType(fileSystemObject, DirectoryInfo)
         Dim fsi As FileSystemInfo
         For Each fsi In  temp.GetFileSystemInfos()
            children.Add(New FileSystemHierarchyData(fsi))
         Next fsi
      End If
      Return children
   End Function 'GetChildren


   Public Overridable Function GetParent() As IHierarchyData _
    Implements IHierarchyData.GetParent
      Dim parentContainer As New FileSystemHierarchicalEnumerable()

      If GetType(DirectoryInfo) Is fileSystemObject.GetType() Then
         Dim temp As DirectoryInfo = CType(fileSystemObject, DirectoryInfo)
         Return New FileSystemHierarchyData(temp.Parent)
      ElseIf GetType(FileInfo) Is fileSystemObject.GetType() Then
         Dim temp As FileInfo = CType(fileSystemObject, FileInfo)
         Return New FileSystemHierarchyData(temp.Directory)
      End If
      ' If FileSystemObj is any other kind of FileSystemInfo, ignore it.
      Return Nothing
   End Function 'GetParent
End Class 'FileSystemHierarchyData
End Namespace

The following code example demonstrates how to declaratively bind a TreeView control to file system data using the FileSystemDataSource example.

<%@ Page Language="VB" %>
<%@ Register Tagprefix="aspSample" Namespace="Samples.AspNet.VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html  >
    <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
        <form id="form1" runat="server">

            <asp:treeview
                id="TreeView1"
                runat="server"
                datasourceid="FileSystemDataSource1" />            

            <aspSample:filesystemdatasource
                id = "FileSystemDataSource1"
                runat = "server" />            

        </form>
    </body>
</html>

.NET Framework Security

Inheritance Hierarchy

System.Object
   System.Web.UI.Control
    System.Web.UI.HierarchicalDataSourceControl
       System.Web.UI.WebControls.SiteMapDataSource
       System.Web.UI.WebControls.XmlDataSource
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms

Windows 98, Windows Server 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

Version Information

.NET Framework

Supported in: 3.0, 2.0
See Also

Community Content

WinForms TreeView Databinding
Added by:MollyBos - MSFT

I would like to do something similar to this, but using WinForms not WebForms. Does anyone know of any good non ASP examples? Thanks

Response :  This isn't the right place for questions; please post questions to the MSDN Forums, at http://forums.microsoft.com/msdn , instead.  If you get a useful response, you can post that info here in the community content section.  Thanks!

Error found on the example above.
Added by:Daniel Portella

the example above has bug, which when run it will loop forever calling GetHierarchicalView method. reason being is that the FileSystemDataSourceView object returned by the implementation of this method on FileSystemDataSource will always return the same view from the first time it was called. see how to fix this bug below:

remove:

Lines,

// Return a strongly typed view for the current data source control.
private FileSystemDataSourceView view = null;

add replace the method

protected override HierarchicalDataSourceView GetHierarchicalView(string viewPath){
if (null == view) {
view = new FileSystemDataSourceView(viewPath);
}
return view;
}

with

protected override HierarchicalDataSourceView GetHierarchicalView(string viewPath)
{
return new FileSystemDataSourceView(viewPath);
}

and on the FileSystemDataSourceView

on the implementation of the method public override IHierarchicalEnumerable Select()

replace the following line

DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);

with

DirectoryInfo rootDirectory = new DirectoryInfo(rootPath + _viewPath);

after you have done that rebuild solution and run your test page.

that will only work if set the MaxDataBindDepth of the treeview control to 1 if you set it to -1 (which will expand fully) the example will fall over when it tries to get a sub folder in one of the folders listed.

Edited :

have a fix the for the problem above replace the filesystemdatasource class with this one (note that the code below is just to get the example to work, i have not made any effort to make the code lean i will leave that to you).

[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
public class FileSystemDataSource : HierarchicalDataSourceControl, IHierarchicalDataSource
{
public FileSystemDataSource() : base() { }
private string _previousViewPath;

protected override HierarchicalDataSourceView GetHierarchicalView(string viewPath)
{
if (_previousViewPath == null)
{
this._previousViewPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath);
}
DirectoryInfo currentViewPath = new DirectoryInfo(this._previousViewPath + viewPath);

Label_78d:
if (currentViewPath.Exists)
{
this._previousViewPath = currentViewPath.FullName;
return new FileSystemDataSourceView(currentViewPath.FullName);
}
else
{
currentViewPath = new DirectoryInfo(_previousViewPath + @"\" + viewPath);
if (currentViewPath.Exists)
{
this._previousViewPath = _previousViewPath + @"\" + viewPath;
return new FileSystemDataSourceView(currentViewPath.FullName);
}
else
{
_previousViewPath = _previousViewPath.Substring(0, _previousViewPath.LastIndexOf("\\"));
currentViewPath = new DirectoryInfo(_previousViewPath + @"\" + viewPath);
goto Label_78d;
}
}
}

// The FileSystemDataSource can be used declaratively. To enable
// declarative use, override the default implementation of
// CreateControlCollection to return a ControlCollection that
// you can add to.
protected override ControlCollection CreateControlCollection()
{
return new ControlCollection(this);
}
}

Source After bug-fix
Added by:Heroic

[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
public class FileSystemDataSource : HierarchicalDataSourceControl, IHierarchicalDataSource
{
public FileSystemDataSource() : base() { }

// Return a strongly typed view for the current data source control.
protected override HierarchicalDataSourceView GetHierarchicalView(string viewPath)
{
if (viewPath.CompareTo(String.Empty) == 0)
{
viewPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath);
}
return new FileSystemDataSourceView(viewPath);
}

// The FileSystemDataSource can be used declaratively. To enable
// declarative use, override the default implementation of
// CreateControlCollection to return a ControlCollection that
// you can add to.
protected override ControlCollection CreateControlCollection()
{
return new ControlCollection(this);
}
}
// The FileSystemDataSourceView class encapsulates the
// capabilities of the FileSystemDataSource data source control.
public class FileSystemDataSourceView : HierarchicalDataSourceView
{
private string _viewPath;

public FileSystemDataSourceView(string viewPath)
{
// This implementation of HierarchicalDataSourceView does not
// use the viewPath parameter but other implementations
// could make use of it for retrieving values.
_viewPath = viewPath;
}

// Starting with the rootNode, recursively build a list of
// FileSystemInfo nodes, create FileSystemHierarchyData
// objects, add them all to the FileSystemHierarchicalEnumerable,
// and return the list.
public override IHierarchicalEnumerable Select()
{
HttpRequest currentRequest = HttpContext.Current.Request;

// SECURITY: There are many security issues that can be raised
// SECURITY: by exposing the file system structure of a Web server
// SECURITY: to an anonymous user in a limited trust scenario such as
// SECURITY: a Web page served on an intranet or the Internet.
// SECURITY: For this reason, the FileSystemDataSource only
// SECURITY: shows data when the HttpRequest is received
// SECURITY: from a local Web server. In addition, the data source
// SECURITY: does not display data to anonymous users.
if (currentRequest.IsAuthenticated &&
(currentRequest.UserHostAddress == "127.0.0.1" ||
currentRequest.UserHostAddress == "::1"))
{
DirectoryInfo rootDirectory = new DirectoryInfo(_viewPath);

FileSystemHierarchicalEnumerable fshe = new FileSystemHierarchicalEnumerable();

foreach (FileSystemInfo fsi in rootDirectory.GetFileSystemInfos())
{
fshe.Add(new FileSystemHierarchyData(fsi));
}
return fshe;
}
else
{
throw new NotSupportedException("The FileSystemDataSource only " + "presents data in an authenticated, localhost context.");
}
}
}
// A collection of FileSystemHierarchyData objects
public class FileSystemHierarchicalEnumerable : ArrayList, IHierarchicalEnumerable
{
public FileSystemHierarchicalEnumerable()
: base()
{
}

public IHierarchyData GetHierarchyData(object enumeratedItem)
{
return enumeratedItem as IHierarchyData;
}
}

public class FileSystemHierarchyData : IHierarchyData
{
public FileSystemHierarchyData(FileSystemInfo obj)
{
fileSystemObject = obj;
}

private FileSystemInfo fileSystemObject = null;

public override string ToString()
{
return fileSystemObject.Name;
}
// IHierarchyData implementation.
public bool HasChildren
{
get
{
if (typeof(DirectoryInfo) == fileSystemObject.GetType())
{
DirectoryInfo temp = (DirectoryInfo)fileSystemObject;
return (temp.GetFileSystemInfos().Length > 0);
}
else return false;
}
}
// DirectoryInfo returns the OriginalPath, while FileInfo returns
// a fully qualified path.
public string Path
{
get
{
return fileSystemObject.FullName;
}
}
public object Item
{
get
{
return fileSystemObject;
}
}
public string Type
{
get
{
return "FileSystemData";
}
}
public IHierarchicalEnumerable GetChildren()
{
FileSystemHierarchicalEnumerable children =
new FileSystemHierarchicalEnumerable();

if (typeof(DirectoryInfo) == fileSystemObject.GetType())
{
DirectoryInfo temp = (DirectoryInfo)fileSystemObject;
foreach (FileSystemInfo fsi in temp.GetFileSystemInfos())
{
children.Add(new FileSystemHierarchyData(fsi));
}
}
return children;
}

public IHierarchyData GetParent()
{
FileSystemHierarchicalEnumerable parentContainer =
new FileSystemHierarchicalEnumerable();

if (typeof(DirectoryInfo) == fileSystemObject.GetType())
{
DirectoryInfo temp = (DirectoryInfo)fileSystemObject;
return new FileSystemHierarchyData(temp.Parent);
}
else if (typeof(FileInfo) == fileSystemObject.GetType())
{
FileInfo temp = (FileInfo)fileSystemObject;
return new FileSystemHierarchyData(temp.Directory);
}
// If FileSystemObj is any other kind of FileSystemInfo, ignore it.
return null;
}
}

// ENJOY!!

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View