Skip to content

Rackspace Cloud Files Code Samples

Carolyn Van Slyck edited this page Aug 9, 2016 · 39 revisions

CloudFilesProvider Samples

Here we will provide samples for basic operation on CloudFilesProvider.

CloudServersProvider requries we pass in CloudIdentity. We can create CloudIdentity by passing any 2 combination Username/Password or Username/APIKey.

var cloudIdentity = new CloudIdentity() { Username = "username", Password = "password" };

or

var cloudIdentity = new CloudIdentity() { APIKey = "apikey", Username = "username" };

For more information on IdentityProvider

There are 2 ways to pass in the identity credentials to CloudFilesProvider:

  1. In the constructor.

  2. Into each method individually.

Our samples below will assume the identity has been passed into the constructor.

Container

Create Container

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
ObjectStore createContainerResponse = cloudFilesProvider.CreateContainer("Container Name");

Note: If you don't pass in region, default region is assumed. Here is an example with region.

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
ObjectStore createContainerResponse = cloudFilesProvider.CreateContainer("Container Name",region:"DFW");

Check the createContainerResponse for status ObjectStore.ContainerCreated for container creation.

Here are the ObjectStore values.

Unknown

ContainerCreated

ContainerExists

ContainerDeleted

ContainerNotEmpty

ContainerNotFound

ObjectDeleted

ObjectCreated

ObjectPurged

Delete Container

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
ObjectStore containerDeleteResponse = cloudFilesProvider.DeleteContainer("Container Name");

Check the containerDeleteResponse for status ObjectStore.ContainerDeleted for container deletion.

List Container in default region

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
IEnumerable<Container> containerList = cloudFilesProvider .ListContainers();

List Container in specific region

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
IEnumerable<Container> containerList = cloudFilesProvider.ListContainers(region:"ord");

List Objects in Container

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
IEnumerable<ContainerObject> containerObjectList = cloudFilesProvider.ListObjects("container name");

Make Container Public (CDN Enable)

This is a Rackspace only feature.

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.EnableCDNOnContainer("container name");

Make Container Private (CDN Disable)

This is a Rackspace only feature.

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.DisableCDNOnContainer("container name"); 

Generate Temporary Public URL

If you can't use CDN enabled containers, you can use the Temp URL functionality to create special URLs which grant an anonymous user access to a file. In the example below, a URL is generated which grants read access for 1 day.

Note that your account must have a Temp-URL-Key account metadata value set first. This value should be set once, and then reused. Changing the Temp-URL-Key will invalidate previously generated temp URLs.

using System;
using System.Collections.Generic;
using JSIStudios.SimpleRESTServices.Client;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;

namespace TempURL
{
    class Program
    {
        static void Main(string[] args)
        {
            var region = "{region}";
            // See https://github.com/openstacknetsdk/openstack.net/wiki/Connect-and-Authenticate#example for how to authenticate against OpenStack instead of Rackspace.
            var user = new CloudIdentity
            {
                Username = "{username}",
                APIKey = "{apikey}"
            };

            var cloudfiles = new CloudFilesProvider(user);

            // Create or initialize your account's key used to generate temp urls
            const string accountTempUrlHeader = "Temp-Url-Key";
            var accountMetadata = cloudfiles.GetAccountMetaData(region);
            string tempUrlKey;
            if (!accountMetadata.ContainsKey(accountTempUrlHeader))
            {
                tempUrlKey = Guid.NewGuid().ToString();
                var updateMetadataRequest = new Dictionary<string, string> { {accountTempUrlHeader, tempUrlKey}};
                cloudfiles.UpdateAccountMetadata(updateMetadataRequest, region);
            }
            else
            {
                tempUrlKey = accountMetadata[accountTempUrlHeader];
            }

            // Generate a public URL for a cloud file which is good for 1 day
            var containerName = "{container-name}";
            var fileName = "{file-name}";
            var expiration = DateTimeOffset.UtcNow + TimeSpan.FromDays(1);
            Uri tempUrl = cloudfiles.CreateTemporaryPublicUri(HttpMethod.GET, containerName, fileName, tempUrlKey, expiration, region);
        }
    }
}

Enable Static on Container

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.EnableStaticWebOnContainer("container name", "web index", "web error", "web listings css", "web listing");

Disable Static on Container

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.DisableStaticWebOnContainer("container name");

Files (Objects)

Creating Objects from Stream

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
var fileName = "file_name.jpg";
using(var stream = System.IO.File.OpenRead("c:\filepath\file_name.jpg")){
    cloudFilesProvider.CreateObject("container name", stream, "object_save_name.jpg");
}

Creating Objects from File

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.CreateObjectFromFile("container name", @"c:\directory\test.jpg", "test.jpg");

Save Object to File

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.GetObjectSaveToFile("container name", @"c:\\save Directory\\", "test.jpg");

Delete Object

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
ObjectStore deleteObjectResponse = cloudFilesProvider.DeleteObject("container name", "test.jpg");

Copy Object from one container to another

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
ObjectStore copyObjectResponse = cloudFilesProvider.CopyObject("source container name", "source object name", "destination container name", "destination object name");

Copy Object from one container to another using Internal URL

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
ObjectStore copyObjectResponse = cloudFilesProvider.CopyObject("source container name", "source object name", "destination container name", "destination object name", useInternalUrl:true);

Purge Public Object from container

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.PurgeObjectFromCDN("container name", "object name");

Create subdirectories in a container

Containers cannot be nested, however you can simulate subdirectories by using URL path separators in the object name. In the example below, the object name is thumbnails/tiny-logo.png and the resulting public URL of the file is: http://abc123.r27.cf1.rackcdn.com/thumbnails/logo.png.

using System;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;

namespace CloudFileSubdirectories
{
    public class Program
    {
        public static void Main()
        {
            // Authenticate
            const string region = "DFW";
            var user = new CloudIdentity
            {
                Username = "username",
                APIKey = "apikey"
            };
            var cloudfiles = new CloudFilesProvider(user);

            // Create a container
            cloudfiles.CreateContainer("images", region: region);

            // Make the container publically accessible
            long ttl = (long)TimeSpan.FromMinutes(15).TotalSeconds;
            cloudfiles.EnableCDNOnContainer("images", ttl, region);
            var cdnInfo = cloudfiles.GetContainerCDNHeader("images", region);
            string containerPrefix = cdnInfo.CDNUri;

            // Upload a file to a "subdirectory" in the container
            cloudfiles.CreateObjectFromFile("images", @"C:\tiny-logo.png", "thumbnails/logo.png", region: region);

            // Print out the URL of the file
            Console.WriteLine($"Uploaded to {containerPrefix}/thumbnails/logo.png");
            // Uploaded to http://abc123.r27.cf1.rackcdn.com/thumbnails/logo.png
        }
    }
}

##Troubleshooting

Error:The user does not have access to the requested service or region.

There is a possibility that default region is not set for your account. Try passing in the optional region parameter. For example: cloudFileProvider.ListContainers(region: “DFW”);