Listing the data sets in a library within your custom task

A SAS Professionals attendee and Twitter follower named Marco asks for help:

..struggling to find a method with custom tasks in EG to be able to list the datasets in a library, can you help please?

Sure, no problem. This is easy-peasy-lemon-squeezy.

First, make sure that you have a reference to the SAS.Tasks.Toolkit.dll in your custom task project. If you used the Visual Studio template to set it up, you've got it.

The SAS task toolkit library provides many easy-to-use classes to help your custom tasks deal with SAS servers, libraries, and data, including:

SAS.Tasks.Toolkit.SasServer
Represents the basic attributes of a SAS server, including its name, host, and connectivity status.

SAS.Tasks.Toolkit.Data.SasLibrary
Represents a SAS library including its descriptive name (from metadata), libref, library engine, and more.

SAS.Tasks.Toolkit.SasServer.SasData
Represents a SAS data set and provides access to data set attributes and columns.

SAS.Tasks.Toolkit.SasServer.SasColumn
Represents a SAS column and its attributes (name, type, format, and more).

To accomplish what Marco is looking to do, the C# code looks something like:

using SAS.Tasks.Toolkit.Data;
...
// Get a library object
SasLibrary lib = new SasLibrary("Local", "SASHELP");
System.Diagnostics.Debug.WriteLine(string.Format("Data members in: {0}", lib.Name));
// list each data set name
foreach (SasData d in lib.GetSasDataMembers())
{
System.Diagnostics.Debug.WriteLine(string.Format(" Data member: {0}", d.Member));
}

The output looks like this:

Data members in: SASHELP
Data member: _CMPIDX_
Data member: ADOMSG
Data member: ADSMSG
Data member: AFMSG
Data member: AIR
Data member: ASSCMGR
Data member: BMT
...

Many methods return collections of objects (such as SAS.Tasks.Toolkit.Data.SasLibrary.GetSasDataMembers) that support the enumerating interfaces to enable data binding, making it easy to show a list of data sets or columns in a list view without cumbersome coding.

For example, this snippet puts the data set names into a Windows listbox control:

// lbData is System.Windows.Forms.ListBox
lbData.DisplayMember = "Member";
lbData.DataSource = lib.GetSasDataMembers();