Sample ASP.NET Page - WendyA/box-windows-sdk-v2 GitHub Wiki

Notes

SQL connection is stored in web.config. One table schema and 3 stored procedures SQL schema is listed on a separate page: SQL Scripts for Sample .NET Page

This sample .NET page gets the access code on first access. It then stores the access token and the refresh token in the database for use in subsequent requests. A simple loop of the root folders is also written for a simple retrieval example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Box.V2;
using Box.V2.Auth;
using Box.V2.Config;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using Box.V2.Models;
using System.Data.SqlClient;
using System.Data;

namespace BoxTesting
{
    public partial class AuthTesting : System.Web.UI.Page
    {
    public string BoxClientID { get; set; }
    public string BoxClientSecret { get; set; }
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
    public string LoggedInUser { get; set; }
    public string PageURL { get; set; }
    string strSQLConn = "";

protected async void Page_Load(object sender, EventArgs e)
        {
        BoxClientID = "Your client id";
        BoxClientSecret = "Your secret id";
        PageURL = "http://localhost:12022/AuthTesting.aspx"; //Your page address

        GetLoggedInUser();
        GetBoxTokensFromDatabase();
        try
        {
            if (RefreshToken != null)
            {
                OAuthSession session = new OAuthSession(AccessToken, RefreshToken, 3600, "bearer");
                var config = new BoxConfig(BoxClientID, BoxClientSecret, new Uri(PageURL));
                var client = new BoxClient(config, session);
                session = await client.Auth.RefreshAccessTokenAsync(session.AccessToken);

                //Update access code and refresh token properties and database values with new values
                AccessToken = client.Auth.Session.AccessToken;
                RefreshToken = client.Auth.Session.RefreshToken;
                UpdateBoxTokensInDatabase();

                Task folders = GetFolderItemsAsync("0", client);
                await folders;
            }
            else
            {
                if (Request.QueryString["code"] == null)
                    Response.Redirect("https://www.box.com/api/oauth2/authorize?response_type=code&client_id=YourClientID", false);
                else
                {
                    AccessToken = Request.QueryString["code"];
                    if (AccessToken != "")
                    {
                        //Configure BOX config and client objects
                        var config = new BoxConfig(BoxClientID, BoxClientSecret, new Uri(PageURL));
                        var client = new BoxClient(config);

                        //Create Session 
                        var session = await client.Auth.AuthenticateAsync(AccessToken);

                        //Add Box Access code and refresh token for this user to the database
                        RefreshToken = client.Auth.Session.RefreshToken;
                        AddBoxTokensToDatabase();

                        //Get Folders
                        Task folders = GetFolderItemsAsync("0", client);
                        await folders;
                    }
                    else
                        Response.Write("Couldn't retrieve access token");
                }
            }  
        }
        catch (Exception ex)
        {
            Response.Write("Page Load " + ex.Message + "  " + ex.StackTrace);
        }
    }

    //Box Methods
    public async Task InitializeBox(string authCode, BoxClient client)
    {
        var session = await client.Auth.AuthenticateAsync(authCode);
    }

    public async Task GetFolderItemsAsync(string id, BoxClient client)
    {
        string FolderName = string.Empty;
        int itemCount = 0;
        int ItemLimit = 10;

        BoxFolder folder;
        folder = await client.FoldersManager.GetItemsAsync(id, ItemLimit, itemCount);
        //folder = await client.FoldersManager.GetFolderItemsAsync(id, ItemLimit, 0, null);
        if (folder == null)
        {
            string message = "Unable to get folder items. Please try again later";
            Response.Write(message);
        }
        else
        {
           Response.Write(folder.Name);

           foreach (var i in folder.ItemCollection.Entries)
           {
               Response.Write("  " + i.Name + "<BR>");
           }
        }
    }

    //SQL Methods
    private void GetBoxTokensFromDatabase()
    {
        SqlConnection conn;

        try
        {
            if (strSQLConn == "")
                GetSQLConnectionString();

            conn = new SqlConnection(strSQLConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "BoxTokenGet";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Account", LoggedInUser);

            SqlDataAdapter daDocs = new SqlDataAdapter(cmd);
            DataTable dtToken = new DataTable("Token");
            daDocs.Fill(dtToken);

            if (dtToken.Rows.Count != 0)
            {
                RefreshToken = dtToken.Rows[0]["BoxRefreshToken"].ToString();
                AccessToken = dtToken.Rows[0]["BoxAccessToken"].ToString();
            }
        }
        catch (Exception ex)
        {
            Response.Write("GetBoxRefreshTokenFromDatabase " + ex.Message + ex.StackTrace);
        }
    }

    private void AddBoxTokensToDatabase()
    {
        SqlConnection conn;
        try
        {
            if (strSQLConn == "")
                GetSQLConnectionString();
            conn = new SqlConnection(strSQLConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "BoxTokenInsert";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@BoxAccessToken", AccessToken);
            cmd.Parameters.AddWithValue("@BoxRefreshToken", RefreshToken);
            cmd.Parameters.AddWithValue("@Account", LoggedInUser);
            cmd.Parameters.AddWithValue("@CreateDate", DateTime.Now);
            cmd.Parameters.AddWithValue("@LastUpdateDate", DateTime.Now);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write("AddBoxRefreshTokenToDatabase " + ex.Message + ex.StackTrace);
        }
        finally
        {
            //if (conn.State == )
            //    conn.Close();

        }
    }

    private void UpdateBoxTokensInDatabase()
    {
        SqlConnection conn;
        try
        {
            if (strSQLConn == "")
                GetSQLConnectionString();
            conn = new SqlConnection(strSQLConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "BoxTokenUpdate";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@BoxAccessToken", AccessToken);
            cmd.Parameters.AddWithValue("@BoxRefreshToken", RefreshToken);
            cmd.Parameters.AddWithValue("@Account", LoggedInUser);
            cmd.Parameters.AddWithValue("@LastUpdateDate", DateTime.Now);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write("UpdateBoxTokensInDatabase " + ex.Message + ex.StackTrace);
        }
        finally
        {
            //if (conn.State == )
            //    conn.Close();

        }
    }

    private void GetSQLConnectionString()
    {
        try
        {
            strSQLConn = System.Configuration.ConfigurationManager.AppSettings["YourDatabaseName"].ToString();
        }
        catch (Exception ex)
        {
            Response.Write("GetSQLConnectionString " + ex.Message);
        }
    }

    //Misc Methods
    private void GetLoggedInUser()
    {
        try
        {
            LoggedInUser = HttpContext.Current.User.Identity.Name.Replace("DomainName\\", String.Empty);  

            //For testing
            if (LoggedInUser == "")
                LoggedInUser = "Test User";
        }
        catch (Exception ex)
        {
            Response.Write("GetLoggedInUser " + ex.Message + ex.StackTrace);
        }
    }
}
}