Monthly Archives: January 2018

Using Egnyte.API package for connecting to Egnyte cloud storage

Egnyte is a company, that offers secure and fast file storage in the cloud for business customers. I have written more about getting started with Egnyte API in my previous post.

Egnyte.API is a nuget package, that I’ve written in .Net and it supports:

  • .Net Framework 4.5
  • Windows Phone 8.1
  • Xamarin

It contains support for most of the functionalities that Egnyte API offers and helps to manage:

  • Files system
  • Permissions
  • Users
  • Groups
  • Search
  • Links
  • Audit reporting

However, if you’d like to improve it, feel free to contribute to it’s github repository.

Obtaining OAuth 2.0 token

First this is obtaining a token, that later can be used for authenticating each request. Egnyte offers three OAuth 2.0 authorization flows: Resource Owner, Authorization Code and Implicit Grant, however Authorization Code flow is the most common. To ease implementation of obtaining the token, Egnyte.API offers helpers methods for all three of those.

public void RequestTokenCode()
    var authorizeUrl = OAuthHelper.GetAuthorizeUri(


public void RequestTokenImplicitGrant()
    var authorizeUrl = OAuthHelper.GetAuthorizeUri(


public async Task<ActionResult> AuthorizeCode(string code)
    var token = await EgnyteClientHelper.GetTokenFromCode(

    return Json(JsonConvert.SerializeObject(token), JsonRequestBehavior.AllowGet);

After you have a token, it’s time to use it.

Usage and structure of Egnyte.API package

The simplest usage is just one line – creating a client.

var client = new EgnyteClient(Token, Domain);

However, you can use optional parameters and pass your own HttpClient if you need to set some specific configuration. After creating a client you are ready to go. Inside a client you will find child clients that will help you use options mentioned above.


Each method is properly named and contains description of it’s usage and purpose of it’s parameters.


Sample usages

This is how folder looks like on the Egnyte web view:

List files

Listing is super easy, code like this:

var client = new EgnyteClient(Token, Domain);
var listing = await client.Files.ListFileOrFolder("Shared/MikTests/Blog");

Returns object, that can be serialized as Json to:


Creating new folder

var listing = await client.Files.CreateFolder("Shared/MikTests/Blog/NewFolder");

Sending a file

var filePath = Server.MapPath("~/Content/myPhoto.jpg");
var stream = new MemoryStream(System.IO.File.ReadAllBytes(filePath));
var listing = await client.Files.CreateOrUpdateFile("Shared/MikTests/Blog/myPhoto.jpg", stream);

Deleting file or folder

var path = "Shared/MikTests/Blog/myPhoto.jpg";
var listing = await client.Files.DeleteFileOrFolder(path, entryId: "9355165a-e599-4148-88c5-0d3552493e2f");

Downloading file

var path = "Shared/MikTests/Blog/";
var responseStream = await client.Files.DownloadFileAsStream(path);

Creating a user

var listing = await client.Users.CreateUser(
    new Users.NewUser {
        UserName = "mikTest100",
        ExternalId = Guid.NewGuid().ToString(),
        Email = "",
        FamilyName = "Michał",
        GivenName = "Białecki",
        Active = true,
        AuthType = Users.UserAuthType.SAML_SSO,
        UserType = Users.UserType.StandardUser,
        IdpUserId = "mbialeckiTest100",
        UserPrincipalName = ""

Updating a user

var listing = await client.Users.UpdateUser(
    new Users.UserUpdate
        Id = 12824215695,
        Email = "",
        FamilyName = "Michał",
        GivenName = "Białecki II"


As you see using Egnyte.API nuget package is very simple. I presented only some of it’s capabilities, but if you want more, feel free to contribute to a public repository: And if you have any questions, just let me know 🙂





Getting started with Egnyte API in .Net

Egnyte is a company that provides software for enterprise file synchronization and sharing. Egnyte offers a cloud storage for business users to securely access and share data across the company. API offers RESTful interface, all request and responses are formated as JSON, strings are encoded as UTF-8 and all calls must be done over HTTPS.

First thing you need to have is your domain and API Key for authorization, you can find whole registration process described here.

Egnyte Api uses OAuth 2.0 for authentication and it supports Resource Owner flow (for internal application, that will be used only by your business internally) and Authorization Code and Implicit Grant for publicly available applications. Once you get the OAuth 2.0 token, you should cache it to use for multiple requests, instead of asking for a key every time you use API. Every subseqent API call would need to add a authorization header with generated token.

Authorization: Bearer 2v8q2bc6uvxtgghwmwvnvcp4

Getting token with Authorization Code flow

Whole process of obtaining token with Authorization Code flow is described here.

I have created a helper method to handle this process.

using Newtonsoft.Json;
public static async Task<TokenResponse> GetTokenFromCode(
    string userDomain,
    string clientId,
    string clientSecret,
    Uri redirectUri,
    string authorizationCode,
    HttpClient httpClient = null)
    var disposeClient = httpClient == null;
        httpClient = httpClient ?? new HttpClient();
        var requestParameters = OAuthHelper.GetTokenRequestParameters(
        var content = new FormUrlEncodedContent(requestParameters.QueryParameters);
        var result = await httpClient.PostAsync(requestParameters.BaseAddress, content).ConfigureAwait(false);

        var rawContent = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

        return JsonConvert.DeserializeObject<TokenResponse>(rawContent);
        if (disposeClient)

Here is a GetTokenRequestParameters method in OAuthHelper class. All it’s parameters are required.

public static class OAuthHelper
    private const string EgnyteBaseUrl = "https://{0}";

    public static TokenRequestParameters GetTokenRequestParameters(
        string userDomain,
        string clientId,
        string clientSecret,
        Uri redirectUri,
        string authorizationCode)
        var queryParameters = new Dictionary<string, string>
                { "client_id", clientId },
                { "client_secret", clientSecret },
                { "redirect_uri", redirectUri.ToString() },
                { "code", authorizationCode },
                { "grant_type", "authorization_code" }

        return new TokenRequestParameters
                BaseAddress = new Uri(string.Format(EgnyteBaseUrl, userDomain)),
                QueryParameters = queryParameters

All code posted here is a part of Egnyte.Api nuget package, that you can download and use yourself. If you’re interested in looking into code, it’s available in github public repository.

Implementing OData in ASP.Net API

OData is a protocol that allows creating custom queries to simple REST services. Using OData query parameters you can filter, sort or transform output you’re getting to fit your needs without any implementation changes on the API side. It sounds groundbreaking and innovative and it actually is, but it’s not a new thing – Microsoft introduced it in 2007.

Is it a lot of work to introduce OData to existing API?

No! It is surprisingly easy. Let’s try it on a simple WebApi controller in a ASP.NET framework. First you need to install nuget package: Microsoft.Data.OData. Let’s say we have a such REST api controller:

public class FoldersController : ApiController
    private IFoldersAndFilesProvider _provider;

    public FoldersController(IFoldersAndFilesProvider provider)
        _provider = provider;

    public IHttpActionResult GetFolders()
        var folders = _provider.GetFolders();
        return Ok(folders);

This is a very simple controller that returns a list of folders in a tree structure. All there is need to be done to make this endpoint OData friendly, we need to change endpoints attributes and return IQueryable result.

public IQueryable<Folder> GetFolders()
    var folders = _provider.GetFolders();
    return folders.AsQueryable();

And this is it! So…

Let’s see some magic

Plain old REST endpoint would return all folders, but with OData we can query that output.


Will return the same full result.


This query will sort the output by folders size.


There is a way to return only few results.


Or use for returning partial result or even paging.

http://localhost:51196/odata/Folders?$filter=Folders/all(folder: folder/Size ge 10000)

More complex query can get folders only above certain size.

http://localhost:51196/odata/Folders?$filter=Folders/all(f: f/Hidden eq false)

Or only those that are not hidden.

You can find more examples like this here.

Not only getting data

OData is perfect for querying data, but it also can be used for adding, updating, patching and deleting entities. In Visual Studio you can add a ODataController and it will prepare a controller for you with pre-generated CRUD operations that you can use.


There are good developer articles about OData here.

This post is just scratching the surface and Microsoft implementation offers a lot, but it offers only a subset of OData features. Works on this subject seems to stop a few years ago, but there’s a new hope on the horizon. Microsoft is working on OData support for .Net Core APIs. You can track progress in this gitub repository. And here you can find some guidelines how to start using this new package.

What can I use it for

OData offers query options for simple REST APIs, that would normally require a lot of developers work to handle all the cases. In my opinion OData is perfect for scenarios where you serve data for many clients that needs different data. It could be a perfect API for automatition tests, that can fetch data that they need at the moment, without hardcoding them. Also it can be a nice addon for APIs that you don’t intend to maintain actively.

All code posted here is also available in my github repo here.