How to connect to the Fuga Cloud ObjectStore using .NET Core
dotNET Core Object Store C-Sharp

How to connect to the Fuga Cloud ObjectStore using .NET Core

The possibilities with the Fuga Object Store are endless. One of the scenarios is connecting your .NET Core application to the Fuga Object Store, this way you can access for example files on your Object Store! In this tutorial we will teach you how to make a simple .NET Core MVC file upload application that uses the Fuga Object Store.

Requirements

API keys

To connect to your Fuga Object Store access and secret keys are required. If you already have these you can skip this chapter.

  1. To list and create API keys for the Object Store we need the Fuga Openstack CLI. If you haven’t installed it yet checkout our tutorial.

  2. After following the tutorial for your operating system it’s time to list the credentials. We need the credentials to access our Object Store container in later steps.

  3. To list all the credentials, enter the command:

    openstack ec2 credentials list
    
  4. If the list of credentials is empty, a new pair of credentials can be generated with:

    openstack ec2 credentials create
    
  5. Either copy the Access and Secret key to clipboard or save them temporarily.

Creating a Fuga Object Store container

  1. Open your Fuga Dashboard and open the ‘Object Store’ section.

  2. Click on ‘Containers’ and create a new container.

We now have a container that is ready to be used in the upcoming steps.

Creating a new .NET Core project

In this chapter we will be creating a .NET core project using a template with MVC.

  1. Create a new folder for the .NET Core project:

    mkdir fugadotnet
    
  2. Open the folder in your terminal with the following command:

    cd fugadotnet
    
  3. Create a new empty .NET Core ASP project by executing the following command:

    dotnet new web
    

    An empty web project will be in your fugadotnet directory.

  4. Create a new folder inside your fugadotnet folder called Controllers:

    mkdir Controllers
    
  5. Create a new folder inside your fugadotnet folder called Views:

    mkdir Views
    
  6. Go inside the Views folder with the following command:

    cd Views
    
  7. Inside the Views folder, create a new folder called ObjectStore.

    Enter the following command:

    mkdir ObjectStore
    

    This is the name of the controller that we will create in the next chapter, feel free to change this.

  8. Open this project in your favorite IDE or text editor, for example Visual Code or Atom.

Adding the AWS .NET S3 SDK to your project

The Fuga Object Store is Amazon S3 compatible, that’s why we can use the official Amazon SDK. In this chapter we will be installing the AWS S3 SDK package to our .NET Core project.

  1. In your terminal execute the following command in your project root:

    dotnet add package AWSSDK.S3 --version 3.3.18.3
    

Creating a new Controller

In this chapter we will be creating a Controller, this will contain most of the logic for the Object Store.

  1. Inside your Controllers folder, create a new file called ObjectStoreController.cs within your text editor or with the following command:

    touch ObjectStoreController.cs
    
  2. Open the ObjectStoreController.cs with your text editor and paste in the following code:

    using System;
    using Microsoft.AspNetCore.Mvc;
    using System.IO;
    using Amazon.S3;
    using Amazon.S3.Model;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    
    namespace fugadotnet.Controllers
    {
        public class ObjectStoreController : Controller
        {
            private string container = "YOUR_CONTAINER_NAME_HERE";
    
            private AmazonS3Client fuga = Startup.GetS3Client();
            public IActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public IActionResult Index(string name)
            {
                if (HttpContext.Request.Form.Files != null)
                {
                    var files = HttpContext.Request.Form.Files;
                    foreach (var file in files)
                    {
                        Console.WriteLine(file.FileName);
                        if (file.Length > 0)
                        {
                            UploadObjectToObjectStore(file);
                        }
                    }
                }
                return View();
            }
    
            public IActionResult Get([FromQuery(Name = "name")] string name)
            {
                ViewData["content"] = GetObject(name).Result;
                return View();
            }
    
            async Task<string> GetObject(string name)
            {
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = container,
                    Key = name
                };
                using (GetObjectResponse response = await fuga.GetObjectAsync(request))
                using (Stream responseStream = response.ResponseStream)
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    return reader.ReadToEnd();
                }
            }
            async Task UploadObjectToObjectStore(IFormFile file)
            {
                var result = string.Empty;
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    result = reader.ReadToEnd();
                }
                var request = new PutObjectRequest
                {
                    BucketName = container,
                    Key = file.FileName,
                    ContentBody = result
                };
    
                await fuga.PutObjectAsync(request);
            }
        }
    }
    
  3. Inside your ObjectStoreController.cs, edit the container variable to your container name.

  4. Save the file.

Creating the views

  1. Inside your fugadotnet/Views/ObjectStore folder, create two views with following command:

    touch Index.cshtml Get.cshtml
    
  2. Open Index.cshtml with your text editor and paste in the following:

    <h1>Fuga Object Store file upload</h1>
    <form method="post" enctype="multipart/form-data" asp-controller="ObjectStore" asp-action="Index">
    <div class="form-group">
        <div class="col-md-10">
            <p>Upload one or more files using this form:</p>
            <input type="file" name="files" multiple />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-10">
            <input type="submit" value="Upload" />
        </div>
    </div>
    </form>
    
  3. Save the file.

  4. Open Get.cshtml and paste in the following:

    <b>@ViewData["content"]</b>
    
  5. Save the file.

Attaching our controller to the project and initialising the connection

Before

  1. Open the Startup.cs file located in the project root and paste in the following:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Amazon.Runtime;
    using Amazon.S3;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.HttpsPolicy;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace fugadotnet
    {
        public class Startup
        {
            private static AmazonS3Client client;
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
                AmazonS3Config config = new AmazonS3Config();
                config.ServiceURL = "http://object.api.fuga.io";
                config.ForcePathStyle = true;
                config.SignatureVersion = "2";
                BasicAWSCredentials cred = new BasicAWSCredentials($"{Configuration["AccessKey"]}",
                                                                   $"{Configuration["SecretKey"]}");
                client = new AmazonS3Client(cred, config);
            }
    
            public static AmazonS3Client GetS3Client()
            {
                return client;
            }
    
            public IConfiguration Configuration { get; }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }
    
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=ObjectStore}/{action=Index}/{id?}");
                });
            }
        }
    }
    
  2. Save the file.

Configuring access to your Fuga Object Store container

  1. In your project root, create a new file called appsettings.json:

    touch appsettings.json
    
  2. Copy paste in the following settings:

    {
    "AccessKey": "YOUR_ACCESS_KEY",
    "SecretKey": "YOUR_SECRET_KEY"
    }
    
  3. Replace the YOUR_ACCESS_KEY and YOUR_SECRET_KEY with the keys from the API keys chapter.

  4. Save the file.

Testing the application

  1. Run the application by executing the following command inside your project root folder:

    dotnet run
    

    Your webbrowser will show you a file upload page.

  2. Upload a text file, for example test.txt with Hello, World as content.

  3. Browse to https://localhost:5001/ObjectStore/Get?name=test.txt

Hello, World will be displayed.

Was this article helpful?


Next article:

How to setup GitLab CI/CD on Fuga Cloud

In this tutorial you will learn how to create a CI/CD pipeline that deploys to the Fuga Object Store using GitLab and GitLab runners. GitLab comes with built-in Continuous Integration, Continuous Deployment, and Continuous Delivery support to build, test, and deploy your application. When a commit is made, a CI/CD pipeline will be started. GitLab will notify the runner that a new job is available. This runner will run all the tests defined for the project and will (re)deploy the application when the tests are successful.