Implemented AzureBlobStorageProvider

Added unit tests
Created a specific solution with Azure dependencies

--HG--
branch : dev
This commit is contained in:
Sebastien Ros
2010-04-23 17:39:23 -07:00
parent 152d8dea15
commit 9efcf65058
11 changed files with 807 additions and 4 deletions

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="AzureSDK" value="C:\Program Files\Windows Azure SDK\v1.1\"/>
</appSettings>
</configuration>

View File

@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1CC62F45-E6FF-43D5-84BF-509A1085D994}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Orchard.Azure.Tests</RootNamespace>
<AssemblyName>Orchard.Azure.Tests</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.WindowsAzure.ServiceRuntime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.WindowsAzure.StorageClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="nunit.framework, Version=2.5.2.9222, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\nunit\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Storage\AzureBlobStorageProviderTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Orchard.Azure\Orchard.Azure.csproj">
<Project>{2505AA84-65A6-43D0-9C27-4F44FD576284}</Project>
<Name>Orchard.Azure</Name>
</ProjectReference>
<ProjectReference Include="..\Orchard\Orchard.Framework.csproj">
<Project>{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}</Project>
<Name>Orchard.Framework</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.Azure.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Orchard.Azure.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("21e6aa35-d13d-495b-af35-bc066a1a8bf2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,190 @@
using System;
using System.Configuration;
using System.IO;
using NUnit.Framework;
using System.Diagnostics;
using Orchard.Azure.Storage;
using Microsoft.WindowsAzure;
using System.Linq;
using Microsoft.WindowsAzure.StorageClient;
namespace Orchard.Azure.Tests.Storage {
[TestFixture]
public class AzureBlobStorageProviderTests {
#region Azure Environment initialization
private Process _dsService;
[TestFixtureSetUp]
public void FixtureSetup() {
var count = Process.GetProcessesByName("DSService").Length;
if (count == 0)
{
var start = new ProcessStartInfo
{
Arguments = "/devstore:start",
FileName =
Path.Combine(ConfigurationManager.AppSettings["AzureSDK"], @"bin\csrun.exe")
};
_dsService = new Process { StartInfo = start };
_dsService.Start();
_dsService.WaitForExit();
}
CloudStorageAccount devAccount;
CloudStorageAccount.TryParse("UseDevelopmentStorage=true", out devAccount);
_azureBlobStorageProvider = new AzureBlobStorageProvider("default", false, devAccount);
}
[TestFixtureTearDown]
public void FixtureTearDown() {
if(_dsService != null)
_dsService.Close();
}
[SetUp]
public void Setup() {
// ensure default container is empty before running any test
DeleteAllBlobs();
}
#endregion
private AzureBlobStorageProvider _azureBlobStorageProvider;
private void DeleteAllBlobs() {
foreach(var blob in _azureBlobStorageProvider.Container.ListBlobs()) {
if(blob is CloudBlob) {
((CloudBlob) blob).DeleteIfExists();
}
if (blob is CloudBlobDirectory) {
DeleteAllBlobs((CloudBlobDirectory)blob);
}
}
}
private static void DeleteAllBlobs(CloudBlobDirectory cloudBlobDirectory) {
foreach (var blob in cloudBlobDirectory.ListBlobs()) {
if (blob is CloudBlob) {
((CloudBlob)blob).DeleteIfExists();
}
if (blob is CloudBlobDirectory) {
DeleteAllBlobs((CloudBlobDirectory)blob);
}
}
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetFileShouldOnlyAcceptRelativePath() {
_azureBlobStorageProvider.CreateFile("foo.txt");
_azureBlobStorageProvider.GetFile("/foot.txt");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetFileThatDoesNotExistShouldThrow() {
_azureBlobStorageProvider.GetFile("notexisting");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void DeleteFileThatDoesNotExistShouldThrow() {
_azureBlobStorageProvider.DeleteFile("notexisting");
}
[Test]
public void CreateFileShouldReturnCorrectStorageFile() {
var storageFile = _azureBlobStorageProvider.CreateFile("foo.txt");
Assert.AreEqual(".txt", storageFile.GetFileType());
Assert.AreEqual("foo.txt", storageFile.GetName());
Assert.That(storageFile.GetPath().EndsWith("/default/foo.txt"), Is.True);
Assert.AreEqual(0, storageFile.GetSize());
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CreateFileShouldThrowAnExceptionIfAlreadyExisting() {
var storageFile = _azureBlobStorageProvider.CreateFile("foo.txt");
Assert.AreEqual(storageFile.GetSize(), 0);
_azureBlobStorageProvider.CreateFile("foo.txt");
}
[Test]
public void RenameFileShouldCreateANewFileAndRemoveTheOld() {
_azureBlobStorageProvider.CreateFile("foo1.txt");
_azureBlobStorageProvider.RenameFile("foo1.txt", "foo2.txt");
var files = _azureBlobStorageProvider.ListFiles("");
Assert.AreEqual(1, files.Count());
Assert.That(files.First().GetPath().EndsWith("foo2.txt"), Is.True);
}
[Test]
public void CreateFileShouldBeFolderAgnostic()
{
_azureBlobStorageProvider.CreateFile("foo.txt");
_azureBlobStorageProvider.CreateFile("folder/foo.txt");
_azureBlobStorageProvider.CreateFile("folder/folder/foo.txt");
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder/folder").Count());
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CreateFolderThatExistsShouldThrow() {
// sebros: In Azure, the folder concept is just about checking files prefix. So until a file exists, a folder is nothing
_azureBlobStorageProvider.CreateFile("folder/foo.txt");
_azureBlobStorageProvider.CreateFolder("folder");
}
[Test]
public void DeleteFolderShouldDeleteFilesAlso() {
_azureBlobStorageProvider.CreateFile("folder/foo1.txt");
_azureBlobStorageProvider.CreateFile("folder/foo2.txt");
_azureBlobStorageProvider.CreateFile("folder/folder/foo1.txt");
_azureBlobStorageProvider.CreateFile("folder/folder/foo2.txt");
Assert.AreEqual(2, _azureBlobStorageProvider.ListFiles("folder").Count());
Assert.AreEqual(2, _azureBlobStorageProvider.ListFiles("folder/folder").Count());
_azureBlobStorageProvider.DeleteFolder("folder");
Assert.AreEqual(0, _azureBlobStorageProvider.ListFiles("folder").Count());
Assert.AreEqual(0, _azureBlobStorageProvider.ListFiles("folder/folder").Count());
}
[Test]
public void ShouldRenameFolders() {
_azureBlobStorageProvider.CreateFile("folder1/foo.txt");
_azureBlobStorageProvider.CreateFile("folder2/foo.txt");
_azureBlobStorageProvider.CreateFile("folder1/folder2/foo.txt");
_azureBlobStorageProvider.CreateFile("folder1/folder2/folder3/foo.txt");
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder1").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder2").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder1/folder2").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder1/folder2/folder3").Count());
_azureBlobStorageProvider.RenameFolder("folder1/folder2", "folder1/folder4");
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder1").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder2").Count());
Assert.AreEqual(0, _azureBlobStorageProvider.ListFiles("folder1/folder2").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder1/folder4").Count());
Assert.AreEqual(1, _azureBlobStorageProvider.ListFiles("folder1/folder4/folder3").Count());
}
}
}

32
src/Orchard.Azure.sln Normal file
View File

@@ -0,0 +1,32 @@

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Orchard.Azure", "Orchard.Azure\Orchard.Azure.csproj", "{2505AA84-65A6-43D0-9C27-4F44FD576284}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Orchard.Azure.Tests", "Orchard.Azure.Tests\Orchard.Azure.Tests.csproj", "{1CC62F45-E6FF-43D5-84BF-509A1085D994}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Orchard.Framework", "Orchard\Orchard.Framework.csproj", "{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2505AA84-65A6-43D0-9C27-4F44FD576284}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2505AA84-65A6-43D0-9C27-4F44FD576284}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2505AA84-65A6-43D0-9C27-4F44FD576284}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2505AA84-65A6-43D0-9C27-4F44FD576284}.Release|Any CPU.Build.0 = Release|Any CPU
{1CC62F45-E6FF-43D5-84BF-509A1085D994}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1CC62F45-E6FF-43D5-84BF-509A1085D994}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1CC62F45-E6FF-43D5-84BF-509A1085D994}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1CC62F45-E6FF-43D5-84BF-509A1085D994}.Release|Any CPU.Build.0 = Release|Any CPU
{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{2505AA84-65A6-43D0-9C27-4F44FD576284}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Orchard.Azure</RootNamespace>
<AssemblyName>Orchard.Azure</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.WindowsAzure.StorageClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Storage\AzureBlobStorageProvider.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Orchard\Orchard.Framework.csproj">
<Project>{2D1D92BB-4555-4CBE-8D0E-63563D6CE4C6}</Project>
<Name>Orchard.Framework</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.Azure")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Orchard.Azure")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("02bb8033-01ce-4c2d-a3f7-2a03641f4640")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,327 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.IO;
using Orchard.Storage;
namespace Orchard.Azure.Storage
{
public interface IDependency {}
public class AzureBlobStorageProvider : IStorageProvider
{
private readonly CloudStorageAccount _storageAccount;
public CloudBlobClient BlobClient { get; private set; }
public CloudBlobContainer Container { get; private set; }
public AzureBlobStorageProvider(string containerName, bool isPrivate) : this(containerName, isPrivate, CloudStorageAccount.FromConfigurationSetting("DataConnectionString"))
{
}
public AzureBlobStorageProvider(string containerName, bool isPrivate, CloudStorageAccount storageAccount)
{
// Setup the connection to custom storage accountm, e.g. Development Storage
_storageAccount = storageAccount;
InitBlobClient(containerName, isPrivate);
}
private void InitBlobClient(string containerName, bool isPrivate)
{
BlobClient = _storageAccount.CreateCloudBlobClient();
// Get and create the container if it does not exist
// The container is named with DNS naming restrictions (i.e. all lower case)
Container = BlobClient.GetContainerReference(containerName);
// Setup the permissions if the container is new
if (Container.CreateIfNotExist()) {
if (isPrivate)
Container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Off });
else
Container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });
}
}
private void EnsurePathIsRelative(string path) {
if(path.StartsWith("/"))
throw new ArgumentException("Path must be relative");
}
private string GetPrefix(string path) {
var prefix = String.Concat(Container.Name, "/", path);
if (prefix.EndsWith("/"))
return prefix;
return String.Concat(prefix, "/");
}
private bool BlobExists(string path) {
if(String.IsNullOrEmpty(path) || path.Trim() == String.Empty)
throw new ArgumentException("Path can't be empty");
try {
var blob = Container.GetBlockBlobReference(path);
blob.FetchAttributes();
return true;
}
catch (StorageClientException e) {
if (e.ErrorCode == StorageErrorCode.ResourceNotFound) {
return false;
}
throw;
}
}
private void EnsureBlobExists(string path)
{
if (!BlobExists(path)) {
throw new ArgumentException("File " + path + " does not exist");
}
}
private void EnsureBlobDoesNotExist(string path)
{
if (BlobExists(path)) {
throw new ArgumentException("File " + path + " already exists");
}
}
private bool DirectoryExists(string path)
{
if (String.IsNullOrEmpty(path) || path.Trim() == String.Empty)
throw new ArgumentException("Path can't be empty");
return Container.GetDirectoryReference(path).ListBlobs().Count() > 0;
}
private void EnsureDirectoryExists(string path)
{
if (!DirectoryExists(path)) {
throw new ArgumentException("Directory " + path + " does not exist");
}
}
private void EnsureDirectoryDoesNotExist(string path)
{
if (DirectoryExists(path)) {
throw new ArgumentException("Directory " + path + " already exists");
}
}
#region IStorageProvider Members
public IStorageFile GetFile(string path) {
EnsurePathIsRelative(path);
EnsureBlobExists(path);
return new AzureBlobFileStorage(Container.GetBlockBlobReference(path));
}
public IEnumerable<IStorageFile> ListFiles(string path)
{
EnsurePathIsRelative(path);
foreach (var blobItem in BlobClient.ListBlobsWithPrefix(GetPrefix(path)).OfType<CloudBlockBlob>()) {
yield return new AzureBlobFileStorage(blobItem);
}
}
public IEnumerable<IStorageFolder> ListFolders(string path)
{
EnsurePathIsRelative(path);
if (!DirectoryExists(path))
{
try {
CreateFolder(path);
}
catch (Exception ex) {
throw new ArgumentException(string.Format("The folder could not be created at path: {0}. {1}", path, ex));
}
}
return Container.GetDirectoryReference(path)
.ListBlobs()
.OfType<CloudBlobDirectory>()
.Select<CloudBlobDirectory, IStorageFolder>(d => new AzureBlobFolderStorage(d))
.ToList();
}
public void CreateFolder(string path) {
EnsurePathIsRelative(path);
EnsureDirectoryDoesNotExist(path);
Container.GetDirectoryReference(path);
}
public void DeleteFolder(string path) {
EnsureDirectoryExists(path);
foreach (var blob in Container.GetDirectoryReference(path).ListBlobs()) {
if (blob is CloudBlob)
((CloudBlob)blob).Delete();
if (blob is CloudBlobDirectory)
DeleteFolder(blob.Uri.ToString());
}
}
public void RenameFolder(string path, string newPath) {
EnsurePathIsRelative(path);
EnsurePathIsRelative(newPath);
if ( !path.EndsWith("/") )
path += "/";
if ( !newPath.EndsWith("/") )
newPath += "/";
foreach ( var blob in Container.GetDirectoryReference(path).ListBlobs() ) {
if ( blob is CloudBlob ) {
string filename = Path.GetFileName(blob.Uri.ToString());
string source = String.Concat(path, filename);
string destination = String.Concat(newPath, filename);
RenameFile(source, destination);
}
if ( blob is CloudBlobDirectory ) {
string foldername = blob.Uri.Segments.Last();
string source = String.Concat(path, foldername);
string destination = String.Concat(newPath, foldername);
RenameFolder(source, destination);
}
}
}
public void DeleteFile(string path) {
EnsurePathIsRelative(path);
EnsureBlobExists(path);
var blob = Container.GetBlockBlobReference(path);
blob.Delete();
}
public void RenameFile(string path, string newPath) {
EnsurePathIsRelative(path);
EnsurePathIsRelative(newPath);
EnsureBlobExists(path);
EnsureBlobDoesNotExist(newPath);
var blob = Container.GetBlockBlobReference(path);
var newBlob = Container.GetBlockBlobReference(newPath);
newBlob.CopyFromBlob(blob);
blob.Delete();
}
public IStorageFile CreateFile(string path) {
EnsurePathIsRelative(path);
if (BlobExists(path)) {
throw new ArgumentException("File " + path + " already exists");
}
var blob = Container.GetBlockBlobReference(path);
blob.OpenWrite().Dispose(); // force file creation
return new AzureBlobFileStorage(blob);
}
public string Combine(string path1, string path2) {
EnsurePathIsRelative(path1);
EnsurePathIsRelative(path2);
if (path1 == null || path2 == null)
throw new ArgumentException("One or more path is null");
if (path1.Trim() == String.Empty)
return path2;
if (path2.Trim() == String.Empty)
return path1;
var uri1 = new Uri(path1);
var uri2 = new Uri(path2);
return uri2.IsAbsoluteUri ? uri2.ToString() : new Uri(uri1, uri2).ToString();
}
#endregion
private class AzureBlobFileStorage : IStorageFile {
private readonly CloudBlockBlob _blob;
public AzureBlobFileStorage(CloudBlockBlob blob) {
_blob = blob;
}
public string GetPath() {
return _blob.Uri.ToString();
}
public string GetName() {
return Path.GetFileName(GetPath());
}
public long GetSize() {
return _blob.Properties.Length;
}
public DateTime GetLastUpdated() {
return _blob.Properties.LastModifiedUtc;
}
public string GetFileType() {
return Path.GetExtension(GetPath());
}
public Stream OpenRead() {
return _blob.OpenRead();
}
public Stream OpenWrite() {
return _blob.OpenWrite();
}
}
private class AzureBlobFolderStorage : IStorageFolder {
private readonly CloudBlobDirectory _blob;
public AzureBlobFolderStorage(CloudBlobDirectory blob) {
_blob = blob;
}
#region IStorageFolder Members
public string GetName() {
return _blob.Uri.ToString();
}
public long GetSize() {
return GetDirectorySize(_blob);
}
public DateTime GetLastUpdated() {
return DateTime.MinValue;
}
public IStorageFolder GetParent() {
if (_blob.Parent != null) {
return new AzureBlobFolderStorage(_blob.Parent);
}
throw new ArgumentException("Directory " + _blob.Uri + " does not have a parent directory");
}
private static long GetDirectorySize(CloudBlobDirectory directoryBlob) {
long size = 0;
foreach (var blobItem in directoryBlob.ListBlobs()) {
if (blobItem is CloudBlob)
size += ((CloudBlob)blobItem).Properties.Length;
if (blobItem is CloudBlobDirectory)
size += GetDirectorySize((CloudBlobDirectory)blobItem);
}
return size;
}
#endregion
}
}
}

View File

@@ -95,7 +95,7 @@ namespace Orchard.Storage {
public void RenameFile(string path, string newPath) {
if (!File.Exists(path)) {
throw new ArgumentException("File " + path + "does not exist");
throw new ArgumentException("File " + path + " does not exist");
}
if (File.Exists(newPath)) {
@@ -105,6 +105,11 @@ namespace Orchard.Storage {
File.Move(path, newPath);
}
public string Combine(string path1, string path2)
{
return Path.Combine(path1, path2);
}
#endregion
private class FileSystemStorageFile : IStorageFile {
@@ -136,8 +141,14 @@ namespace Orchard.Storage {
return _fileInfo.Extension;
}
public Stream OpenStream() {
return new FileStream(_fileInfo.FullName, FileMode.Open);
public Stream OpenRead()
{
return new FileStream(_fileInfo.FullName, FileMode.Open, FileAccess.Read);
}
public Stream OpenWrite()
{
return new FileStream(_fileInfo.FullName, FileMode.Open, FileAccess.ReadWrite);
}
#endregion
@@ -192,5 +203,6 @@ namespace Orchard.Storage {
return size;
}
}
}
}

View File

@@ -8,6 +8,15 @@ namespace Orchard.Storage {
long GetSize();
DateTime GetLastUpdated();
string GetFileType();
Stream OpenStream();
/// <summary>
/// Creates a stream for reading from the file.
/// </summary>
Stream OpenRead();
/// <summary>
/// Creates a stream for writing to the file.
/// </summary>
Stream OpenWrite();
}
}

View File

@@ -11,5 +11,14 @@ namespace Orchard.Storage {
void DeleteFile(string path);
void RenameFile(string path, string newPath);
IStorageFile CreateFile(string path);
/// <summary>
/// Combines two path strings
/// </summary>
/// <param name="path1">The first path</param>
/// <param name="path2">The second path</param>
/// <returns>A string containing the combined paths. If one of the specified paths is a zero-length string, this method returns the other path.
/// If path2 contains an absolute path, this method returns path2.</returns>
string Combine(string path1, string path2);
}
}