Getting started with the new Box .NET SDK

Mateusz Woda
Box Developer Blog
Published in
5 min readMar 12, 2024
source: https://unsplash.com/photos/black-laptop-computer-keyboard-in-closeup-photo-T01GZhBSyMQ

Box recently released a brand new .NET SDK that has full api coverage, fast and predictable updates thanks to the generated nature of the SDK and is even easier to use than the old .NET SDK. It was also recently published to the Nuget, so now it’s the perfect time to learn how to take full advantage of it’s capabilities.

Prerequisites

Create a Box custom JWT app with App + Enterprise Access app access level. Check out Olga Stefaniuk post about JWT authentication if you want to learn how to do this. Also, if you’re curious what other authentication methods you can use in Box apps, check out Alex Novotny post on Box Platform Basics: Authentication Methods 101.

Make sure that you have enabled following scopes:

  • Read all files and folders stored in Box
  • Manage users

From the advanced features include Generate user access tokens.

Also make sure that you re-authorize the application after enabling these settings in Admin Console.

You also need .NET SDK, which can obtained from the official Microsoft website. Currently, the new .NET SDK supports .NET from version 6 and above. You need to download and run appropriate installer from Build apps — SDK section, depending on your operating system.

While Visual Studio is a recommended IDE for writing C# .NET applications, it is not necessary, so you can stick to whatever IDE works best for you.

.NET application setup

To create a new console application execute the following command in your terminal.

dotnet new console --framework net6.0 --name BoxWithNextGenSDK

This command should create a new folder with the same name. Inside this folder you should find project file BoxWithNextGenSDK.csproj and Program.cs which contains the main function — an entry point of the console application. Different versions of .NET can be supplied to the framework argument, depending on what is installed on your machine.

Navigate to this folder and run the following command to add Box.Sdk.Gen as a package dependency.

dotnet add package Box.Sdk.Gen

Finally, run this application to confirm that everything works correctly.

dotnet run

You should see the following output in terminal.

Hello, World!

Using the new .NET Gen SDK with JWT

Download JWT configuration from Box Developer Console by clicking Generate a Public/Private Keypair under Configuration tab.

Rename the downloaded file to config.json and place it in the root folder of the newly created .NET console application.

Add the following piece of code to BoxWithNextGenSdk.csproj to ensure that the config file is included in the compilation output.

  <ItemGroup>
<None Update="config.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

⚠️ Note: Attaching secrets in plain text can be potentially dangerous depending on the use case. It is worth considering other ways to store them safely.

To start using the new Box .NET SDK, include the using directive at the top of the Program.cs file.

using Box.Sdk.Gen;

The new SDK reduces the number of namespaces it provides, so you only need to use a fewer using directives than before. The ones that might be more useful are Box.Sdk.Gen.Schemas — containing all request and response models and Box.Sdk.Gen.Managers — containing all managers that are used to access functions related to particular API features.

To load the config from file into a variable, you can use existing .NET APIs.

var path = "config.json";
var json = File.ReadAllText(path);

The new .NET SDK offers many convenient functions to make it easier to use. One such function allows you to load a configuration directly from a json string.

var jwtConfig = JwtConfig.FromConfigJsonString(json);

Then create an instance of Auth class, which determines which authentication method will be used when communicating with the Box API. Depending on the chosen authentication method you need to use a different class.

var auth = new BoxJwtAuth(jwtConfig);

Finally, create an instance of BoxClient, which is the central point of the SDK through which you can communicate with the Box API.

var client = new BoxClient(auth: auth);

To see if you can use the SDK to communicate with the Box API, try executing a simple API call that displays the name of the current user.

var me = await client.Users.GetUserMeAsync();
Console.WriteLine($"Hello, {me.Name}!");

If you run this code, you should see the output that contains your Box application name. Execute the application with dotnet run command.

Hello, BoxWithNextGenSDK!

If the enterpriseId is present in the configuration file, the SDK will try to authenticate as an enterprise. This happens due to default settings: the sub claim in the request to enterprise and the subject_id to the enterpriseId.

If you want to act as a different user (e.g. as a Managed User), you can clone existing auth object created earlier with userId of user you want to act as and then create new instance of BoxClient with it.

var userClient = new BoxClient(auth.AsUser("user_id"));
var managedUser = await userClient.Users.GetUserMeAsync();
Console.WriteLine($"Hello, {managedUser.Name}!");

Check the authentication documentation if you want to learn how to use different authentication methods.

Getting folder items

The last thing we will look at in this article is how to get all the items in a given folder. The code sample below shows a case of pulling data from the root folder.

var folderItems = await userClient.Folders.GetFolderItemsAsync("0");
if (folderItems.Entries != null)
{
foreach (var item in folderItems.Entries)
{
if (item.FolderMini != null)
{
Console.WriteLine($"Folder: {item.FolderMini.Name}");
}
else if (item.FileFull != null)
{
Console.WriteLine($"File: {item.FileFull.Name}");
}
else if (item.WebLink != null)
{
Console.WriteLine($"WebLink: {item.WebLink.Name}");
}
else
{
Console.WriteLine($"Unknown item: {item}");
}
}
}

Example output should look like this.

Folder: My Box Notes
Folder: My Stuff
File: logs.txt
File: report.pdf

Calling GetFolderItemsAsync returns an object that contains a collection of Entries with all the items in a given folder. Each item can be a Folder, File, or a WebLink. This could be determined based on properties — if the corresponding value of a property is not set to null value, it means that it is an item of that type. If the value of the corresponding property is set to null, it means that the object is not of that type and other propeties should be compared against the null value.

This approach can be seen throughout the SDK when it returns different types of elements in a single collection or property.

And that’s it! If you want to learn more about new generated .NET SDK visit the github page or check the docs. If you’re migrating from the older Box .NET SDK check out the migration guide.

Program.cs source code:

using Box.Sdk.Gen;

var path = "config.json";
var json = File.ReadAllText(path);
var jwtConfig = JwtConfig.FromConfigJsonString(json);
var auth = new BoxJwtAuth(jwtConfig);
var client = new BoxClient(auth: auth);

var me = await client.Users.GetUserMeAsync();
Console.WriteLine($"Hello, {me.Name}!");

var userClient = new BoxClient(auth.AsUser("user_id"));
var managedUser = await userClient.Users.GetUserMeAsync();
Console.WriteLine($"Hello, {managedUser.Name}!");

var folderItems = await userClient.Folders.GetFolderItemsAsync("0");
if (folderItems.Entries != null)
{
foreach (var item in folderItems.Entries)
{
if (item.FolderMini != null)
{
Console.WriteLine($"Folder: {item.FolderMini.Name}");
}
else if (item.FileFull != null)
{
Console.WriteLine($"File: {item.FileFull.Name}");
}
else if (item.WebLink != null)
{
Console.WriteLine($"WebLink: {item.WebLink.Name}");
}
else
{
Console.WriteLine($"Unknown item: {item}");
}
}
}

BoxWithNextGenSDK.csproj content:

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Box.Sdk.Gen" Version="0.2.0" />
</ItemGroup>

<ItemGroup>
<None Update="config.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>

Join our Box Developer Community for support!

--

--