Skip to content

jzhu2009/csharp-cloudfiles

Repository files navigation

Mosso Cloud Files

Description

This is a .NET/C# interface into the Rackspace Mosso Cloud Files service. Cloud Files is reliable, scalable and affordable web-based storage hosting for backing up and archiving all your static content. Cloud Files is the first and only cloud service that leverages a tier one CDN provider to create such an easy and complete storage-to-delivery solution for media content.

Getting dll and using in your project

Go to the downloads page and download the latest version. Unzip the file, unzip the bin zip, and grab the following files:

com.mosso.cloudfiles.dll log4net.dll log4Net.config

Reference them from your application. Look at the examples below once you done this. Example folder structure:

/Your_project /lib /cloudfiles com.mosso.cloudfiles.dll log4net.dll /src …

Getting source, compiling, and using in your project

After you’ve either installed msysgit or cygwin and chosen the git-core package, you can clone this github repository:

git clone git://github.com/rackspace/csharp-cloudfiles.git

This will create the csharp-cloudfiles directory locally on your computer. Go into that folder and run:

build.bat

This will compile the project and give you a resulting dll in …csharp-cloudfiles/bin/debug/

Look above for an example folder structure.

Logging

Logging is done with the log4net.dll and log4net.config file that are included in the source/downloads. You just need to edit the log4net.config file to turn it on:

change: <log4net debug=“false”> to: <log4net debug=“true”> so that logging starts and you get the desired logging output and format.

Currently the log is going to log/com.mosso.cloudfiles.log, where you have the dll referenced.

<file value=“logs/com.mosso.cloudfiles.log” /> (in the log4net.config file)

Please reference the log4net documentation on how to edit that config file.

Testing

Running the tests requires Ruby and Rake to be installed. We suggest you use the One-Click Ruby Installer. Once installed you need to create your integration tests credentials config file.

Run “rake create_credentials_config” from the project solution directory. This will create a Credentials.config file in the com.mosso.cloudfiles.integration.tests project folder:

<?xml version="1.0" encoding="utf-8"?>
<credentials>
  <username>PUT USERNAME HERE</username>
  <api_key>PUT API KEY HERE</api_key>
</credentials>

Just replace the placeholder text. This file *is not* under source control. It is ignored by the .gitignore file.

The unit tests are present but still being worked on.

Forums

Please visit the Mosso Forums if you have any questions. Once you are logged in, scroll to cloud files category/grouping and then the .NET thread.

Examples

See the class definitions for documentation on specific methods and operations.

types are explicitly used in this example. The var keyword could also be used and object/collection initializers could be used. We are being explicit for example

Connect to CloudFiles UserCredentials userCredentials = new UserCredentials(“username”, “api key”); IConnection connection = new Connection(userCredentials);

Get the account information AccountInformation accountInformation = connection.GetAccountInformation();

Get the account information as JSON string jsonReturnValue = connection.GetAccountInformationJson();

Get the account information as XML XmlDocument xmlReturnValue = connection.GetAccountInformationXml();

Create new container connection.CreateContainer(“container name”);

Get container information Container container = connection.GetContainerInformation(“container name”);

Get container information as JSON string jsonResponse = connection.GetContainerInformationJson(“container name”);

Get container information as XML XmlDocument xmlResponse = connection.GetContainerInformationXml(“container name”);

Put item in container with metadata Dictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(“key1”, “value1”); metadata.Add(“key2”, “value2”); metadata.Add(“key3”, “value3”); connection.PutStorageItem(“container name”, “C:LocalFilePathfile.txt”, metadata);

Get all the containers for the account List<string> containers = connection.GetContainers();

Put item in container without metadata connection.PutStorageItem(“container name”, “C:LocalFilePathfile.txt”);

Put item in container from stream with metadata Dictionary{string, string} metadata = new Dictionary{string, string}(); metadata.Add(“key1”, “value1”); metadata.Add(“key2”, “value2”); metadata.Add(“key3”, “value3”); FileInfo file = new FileInfo(“C:LocalFilePathfile.txt”); connection.PutStorageItem(“container name”, file.Open(FileMode.Open), “RemoteFileName.txt”);

Put item in container from stream FileInfo file = new FileInfo(“C:LocalFilePathfile.txt”); connection.PutStorageItem(“container name”, file.Open(FileMode.Open), “RemoteFileName.txt”, metadata);

Make path explicitly with auto-creation of “directory” structure connection.MakePath(“/dir1/dir2/dir3/dir4/file.txt”);

List all the items in a container List<string> containerItemList = connection.GetContainerItemList(“container name”);

Shortening the search results by using parameter dictionary Dictionary<GetItemListParameters, string> parameters = new Dictionary<GetItemListParameters, string>(); parameters.Add(GetItemListParameters.Limit, 2); parameters.Add(GetItemListParameters.Marker, 1); parameters.Add(GetItemListParameters.Prefix, “a”); List<string> containerItemList = connection.GetContainerItemList(“container name”, parameters);

Get item from container StorageItem storageItem = connection.GetStorageItem(“container name”, “RemoteStorageItem.txt”);

Get item from container with request Header fields Dictionary<RequestHeaderFields, string> requestHeaderFields = Dictionary<RequestHeaderFields, string>(); string dummy_etag = “5c66108b7543c6f16145e25df9849f7f”; requestHeaderFields.Add(RequestHeaderFields.IfMatch, dummy_etag); requestHeaderFields.Add(RequestHeaderFields.IfNoneMatch, dummy_etag); requestHeaderFields.Add(RequestHeaderFields.IfModifiedSince, DateTime.Now.AddDays(6).ToString()); requestHeaderFields.Add(RequestHeaderFields.IfUnmodifiedSince, DateTime.Now.AddDays(-6).ToString()); requestHeaderFields.Add(RequestHeaderFields.Range, “0-5”); StorageItem storageItem = connection.GetStorageItem(“container name”, “RemoteStorageItem.txt”, requestHeaderFields);

Get item from container and put straight into local file StorageItem storageItem = connection.GetStorageItem(“container name”, “RemoteStorageItem.txt”, “C:LocalFilePathfile.txt”);

Get item from container and put straight into local file with request Header fields Dictionary<RequestHeaderFields, string> requestHeaderFields = Dictionary<RequestHeaderFields, string>(); string dummy_etag = “5c66108b7543c6f16145e25df9849f7f”; requestHeaderFields.Add(RequestHeaderFields.IfMatch, dummy_etag); requestHeaderFields.Add(RequestHeaderFields.IfNoneMatch, dummy_etag); requestHeaderFields.Add(RequestHeaderFields.IfModifiedSince, DateTime.Now.AddDays(6).ToString()); requestHeaderFields.Add(RequestHeaderFields.IfUnmodifiedSince, DateTime.Now.AddDays(-6).ToString()); requestHeaderFields.Add(RequestHeaderFields.Range, “0-5”); StorageItem storageItem = connection.GetStorageItem(“container name”, “RemoteFileName.txt”, “C:LocalFilePathfile.txt”, requestHeaderFields);

Set meta data information for an item in a container Dictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(“key1”, “value1”); metadata.Add(“key2”, “value2”); metadata.Add(“key3”, “value3”); connection.SetStorageItemMetaInformation(“container name”, “C:LocalFilePathfile.txt”, metadata);

Get item information StorageItem storageItem = connection.GetStorageItemInformation(“container name”, “RemoteStorageItem.txt”);

Get a list of the public containers (on the CDN) List<string> containers = connection.GetPublicContainers();

Mark a container as public (available on the CDN) Uri containerPublicUrl = connection.MarkContainerAsPublic(“container name”); Mark a container as public (available on the CDN), with time-to-live (TTL) parameters Uri containerPublicUrl = connection.MarkContainerAsPublic(“container name”, 12345);

Get public container information Container container = connection.GetPublicContainerInformation(“container name”)

Set TTL on public container connection.SetTTLOnPublicContainer(“container name”, 12345); Mark a container as private (remove it from the CDN) connection.MarkContainerAsPrivate(“container name”); Delete item from container connection.DeleteStorageItem(“container name”, “RemoteStorageItem.txt”);

Delete container connection.DeleteContainer(“container name”); Upload/Download files asychrononously while displaying a progress bar Create a new Windows form with your progress bar control. Using the code below as an example, create upload and download methods in the code behind for the form that take whatever parameters you’re using for the GetStorageItem and PutStorageItem call.

In your main form, when initiating the download/upload, create a new instance of your form and call the appropriate method.

An example of uploading asynchronously: var p = new ProgressDialog();

p.StartFileTransfer(this, Connection, containerName, localFileName);

SetSuccessfulMessageInStatusBar();
//Refresh the container
RetrieveContainerItemList();

Code below is an example of what would go in your progress bar form: public void StartFileTransfer(Form owner, Connection connection, string container, string filePath)

{
    totalTransferred = 0f;
    Text = "Uploading File";
    Cursor = Cursors.WaitCursor;
    var fi = new FileInfo(filePath);
    filesize = fi.Length;
    totalBytesLabel.Text = filesize.ToString();

    connection.AddProgressWatcher(fileTransferProgress);
    connection.OperationComplete += transferComplete;

    connection.PutStorageItemAsync(container, filePath);
    //It's absolutely critical that ShowDialog is called over Show. ShowDialog sets the dialog to modal, blocking input to any
    //other form in the application until the operation is complete. Otherwise, a deadlock occurs if you click the main form,
    //hanging the entire application
    ShowDialog(owner);      
}

private void transferComplete()
{
    if (InvokeRequired)
    {
        Invoke(new CloseCallback(Close), new object[]{});
    }
    else
    {
        if (!IsDisposed)
            Close();
    }
}

private void fileTransferProgress(int bytesTransferred)
{
    if (InvokeRequired)
    {
        Invoke(new FileProgressCallback(fileTransferProgress), new object[] {bytesTransferred});
    }
    else
    {
        System.Console.WriteLine(totalTransferred.ToString());
        totalTransferred += bytesTransferred;
        bytesTransferredLabel.Text = totalTransferred.ToString();
        var progress = (int) ((totalTransferred/filesize)*100.0f);
        if(progress > 100)
            progress = 100;
        transferProgressBar.Value = progress ;
    }
}

public void StartFileDownload(MainForm owner, Connection connection, long filesize, string container, string storageItemName, string localFileName)
{
    Text = "Downloading File";
    Cursor = Cursors.WaitCursor;
    this.filesize = filesize;

    totalBytesLabel.Text = filesize.ToString();

    connection.AddProgressWatcher(fileTransferProgress);
    connection.OperationComplete += transferComplete;

    connection.GetStorageItemAsync(container, storageItemName, localFileName);

    //It's absolutely critical that ShowDialog is called over Show. ShowDialog sets the dialog to modal, blocking input to any
    //other form in the application until the operation is complete. Otherwise, a deadlock occurs if you click the main form,
    //hanging the entire application
    ShowDialog(owner);
}

See the Cloud Files Viewer demo for a more concrete example

Authors

Jason Meridth <jason.meridth@rackspace.com> (armmer)

Matt Dietz <matt.dietz@rackspace.com> (cerberus98)

License

See COPYING for license information. Copyright © 2009, Rackspace US, Inc.

About

C#/.NET API for Rackspace Cloud Files

Resources

License

Stars

Watchers

Forks

Packages

No packages published