Skip to main content

C# SDK Quickstart

Following the steps described on this page you'll create a simple Asp.Net project

If you want to download the complete working example you can find it here.

0️⃣  Prerequisites

In this guide, we assume that these prerequisites are met:

1️⃣  Step One: Create an Asp.Net web app

The first step is to create an Asp.Net web application:

dotnet new webapp -o Quickstart --no-https

Now open the directory created by the above command, in this case, Quickstart/ and proceed to install the Fatture in Cloud SDK, published to Nuget.

To install it using the .NET CLI:

dotnet add package It.FattureInCloud.Sdk

2️⃣  Step Two: Set up the OAuth access token retrieval

Edit the files Pages/Index.cshtml.cs and Pages/Index.cs.cshtml, delete the existing content and paste into them the following snippets:

Index.cshtml.cs
using System;
using System.IO;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using It.FattureInCloud.Sdk.OauthHelper;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Quickstart.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;

public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}

public void OnGet()
{
string code = HttpContext.Request.Query["code"];
var oauth = new OAuth2AuthorizationCodeManager("CLIENT_ID", "CLIENT_SECRET", "http://localhost:5000/oauth");

if (code is null)
{
var scopes = new List<Scope> { Scope.ENTITY_SUPPLIERS_READ };
var url = oauth.GetAuthorizationUrl(scopes, "EXAMPLE_STATE");
Response.Redirect(url);
}
else
{
var token = oauth.FetchToken(code);
using StreamWriter file = new("token.json");

file.Write(JsonConvert.SerializeObject(token)); //saving the oAuth access token in the file token.json in the bin folder
file.Close();

ViewData["Content"] = "Token saved succesfully in token.json in your bin folder";
}
}
}
}

To make this code work properly the only thing you need to set your client id, client secret and eventually the redirect uri in the Index.cshtml.cs file at line 23.

Check the Redirect URL

Make sure your FattureInCloud app redirect URL points at the just edited file (e.g. http://localhost:5000/Index).

Store your Tokens safely!

In this QuickStart the access token and refresh token are stored in a file. This is only for educational purposes, the OAuth access token and refresh token are sensitive data and should be saved securely on your database. Also, never share your Client Secret with third-party actors, or publish it to your frontend!

4️⃣  Step Four: Setup the sample

Create the files Pages/Quickstart.cs.cshtml and Pages/Quickstart.cshtml and copy the following code:

Quickstart.cshtml.cs
using System;
using System.IO;

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using It.FattureInCloud.Sdk.Api;
using It.FattureInCloud.Sdk.Model;
using It.FattureInCloud.Sdk.Client;
using Newtonsoft.Json;

namespace OauthQuickstart.Pages
{
public class QuickstartModel : PageModel
{
private readonly ILogger<QuickstartModel> _logger;

public QuickstartModel(ILogger<QuickstartModel> logger)
{
_logger = logger;
}

public void OnGet()
{
using StreamReader file = new("token.json");

//retrieve the oAuth access token in the file token.json in the bin folder
var line = file.ReadLine();
file.Close();
dynamic json = JsonConvert.DeserializeObject<dynamic>(line);
string accessToken = json.access_token;

Configuration config = new Configuration();
config.AccessToken = accessToken.Replace(@"\", "" );

// Modify the selected supplier
ModifySupplierRequest modifySupplierRequest = new ModifySupplierRequest();
modifySupplierRequest.Data = new Supplier();
modifySupplierRequest.Data.Name = "nuovo nome";
modifySupplierRequest.Data.Phone = "03561234312";

var result = modifyFirstSupplier(config, modifySupplierRequest);

ViewData["Content"] = result;
}

public static string modifyFirstSupplier(Configuration config, ModifySupplierRequest modifySupplierRequest)
{
try
{
var userApiInstance = new UserApi(config);
var suppliersApiInstance = new SuppliersApi(config);

// Retrieve User Companies
var userCompaniesResponse = userApiInstance.ListUserCompanies();
var firstCompanyId = userCompaniesResponse.Data.Companies[0].Id;

// Retrieve the list of the Suppliers for the selected company
var fields = ""; // string | List of comma-separated fields. (optional)
var fieldset = "detailed"; // string | Name of the fieldset. (optional)
var sort = "-id"; // string | List of comma-separated fields for result sorting (minus for desc sorting). (optional)
var page = 2; // int? | The page to retrieve. (optional) (default to 1)
var perPage = 8; // int? | The size of the page. (optional) (default to 5)
var companySuppliers = suppliersApiInstance.ListSuppliers(firstCompanyId, null, fieldset, sort, page, perPage);
var firstSupplierId = companySuppliers.Data[0].Id;

ModifySupplierResponse modifySupplierResponse = suppliersApiInstance.ModifySupplier(firstCompanyId, firstSupplierId, modifySupplierRequest);

return("Supplier modificato correttamente\n" + modifySupplierResponse.Data.ToJson());
}
catch (Exception e)
{
Console.Write(e);
return e.ToString();
}
}
}
}

It's also needed to edit the Pages/Shared/_Layout.cshtml, delete the already existing content and paste the following code:

_Layout.cshtml
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OauthQuickstart</title>
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
</body>
</html>

5️⃣  Step Five: Test the sample

Now you can start a web server running the following command in your shell:

dotnet watch run

Now visit http://localhost:5000/ (or whatever your URL is), you will be redirected to the Fatture in Cloud login page where you will be asked to grant some permissions, according to what scopes you specified previously. Finally, you will see the success message and the access token will be stored in the token.json file.

You can now visit http://localhost:5000/Quickstart (or whatever your URL is) to test the application.

  What now?

In this example, we used a limited set of the available API methods to show how to use our SDK.

If you want to access the full documentation of the available methods and models, you can check the following resources: