Skip to content

Commit

Permalink
Merge pull request #23 from mcarr5/master
Browse files Browse the repository at this point in the history
Mostly code cleanup.
  • Loading branch information
ChrisFulstow committed Nov 17, 2014
2 parents 3b8450f + 6e41456 commit 8578e15
Show file tree
Hide file tree
Showing 27 changed files with 465 additions and 232 deletions.
70 changes: 70 additions & 0 deletions NBlog.Database.SQL/NBlog.Database.SQL.sqlproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<Name>NBlog.Database.SQL</Name>
<SchemaVersion>2.0</SchemaVersion>
<ProjectVersion>4.1</ProjectVersion>
<ProjectGuid>{65ed8171-4a1d-4b77-8c66-5b13a753f343}</ProjectGuid>
<DSP>Microsoft.Data.Tools.Schema.Sql.Sql120DatabaseSchemaProvider</DSP>
<OutputType>Database</OutputType>
<RootPath>
</RootPath>
<RootNamespace>NBlog.Database.SQL</RootNamespace>
<AssemblyName>NBlog.Database.SQL</AssemblyName>
<ModelCollation>1033, CI</ModelCollation>
<DefaultFileStructure>BySchemaAndSchemaType</DefaultFileStructure>
<DeployToDatabase>True</DeployToDatabase>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetLanguage>CS</TargetLanguage>
<AppDesignerFolder>Properties</AppDesignerFolder>
<SqlServerVerification>False</SqlServerVerification>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseSet>True</TargetDatabaseSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\Release\</OutputPath>
<BuildScriptName>$(MSBuildProjectName).sql</BuildScriptName>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\Debug\</OutputPath>
<BuildScriptName>$(MSBuildProjectName).sql</BuildScriptName>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">11.0</VisualStudioVersion>
<!-- Default to the v11.0 targets path if the targets file for the current VS version is not found -->
<SSDTExists Condition="Exists('$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets')">True</SSDTExists>
<VisualStudioVersion Condition="'$(SSDTExists)' == ''">11.0</VisualStudioVersion>
</PropertyGroup>
<Import Condition="'$(SQLDBExtensionsRefPath)' != ''" Project="$(SQLDBExtensionsRefPath)\Microsoft.Data.Tools.Schema.SqlTasks.targets" />
<Import Condition="'$(SQLDBExtensionsRefPath)' == ''" Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" />
<ItemGroup>
<Folder Include="Properties" />
<Folder Include="Tables" />
</ItemGroup>
<ItemGroup>
<Build Include="Tables\dbo.About.sql" />
<Build Include="Tables\dbo.Cloud.sql" />
<Build Include="Tables\dbo.Config.sql" />
<Build Include="Tables\dbo.ContactForm.sql" />
<Build Include="Tables\dbo.Disqus.sql" />
<Build Include="Tables\dbo.Entry.sql" />
</ItemGroup>
</Project>
8 changes: 8 additions & 0 deletions NBlog.Database.SQL/Tables/dbo.About.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE [dbo].[About]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY (1, 1),
[Title] NVARCHAR(250) NOT NULL DEFAULT 'About Me',
[Name] NVARCHAR(250) NOT NULL DEFAULT 'My Name',
[Content] NVARCHAR(MAX) NOT NULL DEFAULT 'Content About Me',
[ImageUrl] NVARCHAR(MAX) NULL
)
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
6 changes: 2 additions & 4 deletions NBlog.Web/App_Start/ContainerConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ namespace NBlog.Web
public class ContainerConfig
{
public static readonly string JsonRepositoryType = ConfigurationManager.AppSettings["JsonRepositoryType"];
private static readonly string ImagesRepositoryType = ConfigurationManager.AppSettings["ImagesRepositoryType"];

public static void SetUpContainer()
{
Expand Down Expand Up @@ -93,8 +92,7 @@ private static IContainer RegisterDependencies()
});

builder.RegisterType<AzureBlobRepository>().Named<IRepository>("azureblob").InstancePerRequest().WithParameters(new[] {
new NamedParameter("keys", repositoryKeys),
new NamedParameter("tenantSelector", new HttpTenantSelector())
new NamedParameter("keys", repositoryKeys)
});

builder.RegisterControllers(typeof(ContainerConfig).Assembly)
Expand All @@ -111,7 +109,7 @@ private static IContainer RegisterDependencies()
.WithParameter(GetResolvedParameterByName<IRepository>(JsonRepositoryType));

builder.RegisterType<ImageService>().As<IImageService>().InstancePerLifetimeScope()
.WithParameter(GetResolvedParameterByName<IRepository>(ImagesRepositoryType));
.WithParameter(GetResolvedParameterByName<IRepository>(ConfigurationManager.AppSettings["ImagesRepositoryType"]));

builder.RegisterType<UserService>().As<IUserService>().InstancePerLifetimeScope();
builder.RegisterType<MessageService>().As<IMessageService>().InstancePerLifetimeScope();
Expand Down
4 changes: 2 additions & 2 deletions NBlog.Web/Application/Service/Entity/Image.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ namespace NBlog.Web.Application.Service.Entity
{
public class Image
{
public string FileName { get; set; }
public string Url { get; set; }
public Stream StreamToUpload { get; set; }
public string Uri { get; set; }
public string FileName { get; set; }
}
}
5 changes: 1 addition & 4 deletions NBlog.Web/Application/Service/IImageService.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
using NBlog.Web.Application.Service.Entity;
using System.Collections.Generic;

namespace NBlog.Web.Application.Service
{
public interface IImageService
{
void Save(Image entry);
void Save(Image stream);
Image GetByFileName(string fileName);
List<Image> GetList();
void Delete(string fileName);
bool Exists(string fileName);
}
}
16 changes: 2 additions & 14 deletions NBlog.Web/Application/Service/Internal/ImageService.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using NBlog.Web.Application.Service.Entity;
using NBlog.Web.Application.Storage;
using System.Collections.Generic;
using System.Linq;

namespace NBlog.Web.Application.Service.Internal
{
Expand All @@ -14,29 +12,19 @@ public ImageService(IRepository repository)
_repository = repository;
}

public void Save(Image image)
public void Save(Image stream)
{
_repository.Save<Image>(image);
_repository.Save<Image>(stream);
}

public Image GetByFileName(string fileName)
{
return _repository.Single<Image>(fileName);
}

public List<Image> GetList()
{
return _repository.All<Image>().ToList();
}

public void Delete(string fileName)
{
_repository.Delete<Image>(fileName);
}

public bool Exists(string fileName)
{
return _repository.Exists<Image>(fileName);
}
}
}
141 changes: 47 additions & 94 deletions NBlog.Web/Application/Storage/Azure/AzureBlobRepository.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using NBlog.Web.Application.Infrastructure;
using NBlog.Web.Application.Service.Entity;
using Newtonsoft.Json;
using System;
Expand All @@ -14,106 +13,77 @@ namespace NBlog.Web.Application.Storage.Azure
public class AzureBlobRepository : IRepository
{
private readonly RepositoryKeys _keys;
private readonly HttpTenantSelector _tenantSelector;
private readonly CloudBlobContainer _jsonContainer;
private readonly CloudBlobContainer _imagesContainer;
private readonly CloudBlobClient _blobClient;

public AzureBlobRepository(RepositoryKeys keys, HttpTenantSelector tenantSelector)
public AzureBlobRepository(RepositoryKeys keys)
{
_keys = keys;
_tenantSelector = tenantSelector;

var storage = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureBlob"].ConnectionString);
var blobClient = storage.CreateCloudBlobClient();
string name = GetContainerSafeName(tenantSelector);
_jsonContainer = blobClient.GetContainerReference(ConfigurationManager.AppSettings["JsonBlobContainerName"]);
_jsonContainer.CreateIfNotExists(BlobContainerPublicAccessType.Off);
_imagesContainer = blobClient.GetContainerReference(ConfigurationManager.AppSettings["ImagesBlobContainerName"]);
_imagesContainer.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
_blobClient = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureBlob"].ConnectionString).CreateCloudBlobClient();
}

private string GetContainerSafeName(HttpTenantSelector selector)
private string GetItemPath<TEntity>(string key)
{
string name = selector.Name;
if (name.Any(c => Char.IsNumber(c)))
name = "localhost";
return name;
string pathFormat = "{0}/{1}";
if (!typeof(TEntity).Equals(typeof(Image)))
{
pathFormat = string.Format("{0}.json", pathFormat);
}
return string.Format(pathFormat, typeof(TEntity).Name.ToLower(), key);
}

private string GetItemPath<TEntity>(string key)
private CloudBlobContainer GetBlobContainer<TEntity>()
{
if (typeof(TEntity).Equals(typeof(Image)))
CloudBlobContainer blobContainer = null;
if (!typeof(TEntity).Equals(typeof(Image)))
{
return string.Format("{0}/{1}", typeof(TEntity).Name.ToLower(), key);
blobContainer = _blobClient.GetContainerReference(ConfigurationManager.AppSettings["JsonBlobContainerName"]);
blobContainer.CreateIfNotExists(BlobContainerPublicAccessType.Off);
}
else
{
return string.Format("{0}/{1}.json", typeof(TEntity).Name.ToLower(), key);
blobContainer = _blobClient.GetContainerReference(ConfigurationManager.AppSettings["ImagesBlobContainerName"]);
blobContainer.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
}
return blobContainer;
}

public TEntity Single<TEntity>(object key) where TEntity : class, new()
{
string relativePath = GetItemPath<TEntity>(key.ToString());
ICloudBlob blob = null;
if (typeof(TEntity).Equals(typeof(Image)))
var blobContainer = GetBlobContainer<TEntity>();
ICloudBlob blob = blobContainer.GetBlockBlobReference(relativePath);
if (!blob.Exists())
{
blob = _imagesContainer.GetBlockBlobReference(relativePath);
if (!blob.Exists())
{
throw new FileNotFoundException("The item '" + relativePath + "' could not be found. Container: " + _imagesContainer.Name + " " + _imagesContainer.Uri);
}
var image = new Image();
image.Url = blob.Uri.AbsoluteUri;
var item = image as TEntity;
return item;
throw new FileNotFoundException("The item '" + relativePath + "' could not be found. Container: " + blobContainer.Name + " " + blobContainer.Uri);
}
else
TEntity item = null;
if (!typeof(TEntity).Equals(typeof(Image)))
{
blob = _jsonContainer.GetBlockBlobReference(relativePath);
if (!blob.Exists())
{
throw new FileNotFoundException("The item '" + relativePath + "' could not be found. Container: " + _jsonContainer.Name + " " + _jsonContainer.Uri);
}
string json = blob.DownloadText();
var item = JsonConvert.DeserializeObject<TEntity>(json);
return item;
item = JsonConvert.DeserializeObject<TEntity>(json);
}
else
{
var image = new Image() { Uri = blob.Uri.AbsoluteUri };
item = image as TEntity;
}
return item;
}

public IEnumerable<TEntity> All<TEntity>() where TEntity : class, new()
{
var list = new List<TEntity>();
CloudBlobDirectory directory = null;
if (typeof(TEntity).Equals(typeof(Image)))
{
directory = _imagesContainer.GetDirectoryReference(typeof(TEntity).Name.ToLower());
}
else
{
directory = _jsonContainer.GetDirectoryReference(typeof(TEntity).Name.ToLower());
}
var blobContainer = GetBlobContainer<TEntity>();
CloudBlobDirectory directory = blobContainer.GetDirectoryReference(typeof(TEntity).Name.ToLower());
var blobs = directory.ListBlobs();

foreach (var blob in blobs)
{
string relativePath = string.Format("{0}{1}", blob.Parent.Prefix, Uri.UnescapeDataString(blob.Uri.Segments.LastOrDefault()));
ICloudBlob b = null;
if (typeof(TEntity).Equals(typeof(Image)))
{
b = _imagesContainer.GetBlockBlobReference(relativePath);
var image = new Image();
image.Url = blob.Uri.AbsoluteUri;
var item = image as TEntity;
list.Add(item);
}
else
{
b = _jsonContainer.GetBlockBlobReference(relativePath);
string json = b.DownloadText();
var entity = JsonConvert.DeserializeObject<TEntity>(json);
list.Add(entity);
}
ICloudBlob b = blobContainer.GetBlockBlobReference(relativePath);
string json = b.DownloadText();
var entity = JsonConvert.DeserializeObject<TEntity>(json);
list.Add(entity);
}

return list;
Expand All @@ -122,51 +92,34 @@ private string GetItemPath<TEntity>(string key)
public bool Exists<TEntity>(object key) where TEntity : class, new()
{
string relativePath = GetItemPath<TEntity>(key.ToString());
ICloudBlob blob = null;
if (typeof(TEntity).Equals(typeof(Image)))
{
blob = _imagesContainer.GetBlockBlobReference(relativePath);
}
else
{
blob = _jsonContainer.GetBlockBlobReference(relativePath);
}
ICloudBlob blob = GetBlobContainer<TEntity>().GetBlockBlobReference(relativePath);
return blob.Exists();
}

public void Save<TEntity>(TEntity item) where TEntity : class, new()
{
var key = _keys.GetKeyValue(item).ToString();
string relativePath = GetItemPath<TEntity>(key);
ICloudBlob blob = null;
if (typeof(TEntity).Equals(typeof(Image)))
var blobContainer = GetBlobContainer<TEntity>();
ICloudBlob blob = blobContainer.GetBlockBlobReference(relativePath);
if (!typeof(TEntity).Equals(typeof(Image)))
{
var json = JsonConvert.SerializeObject(item, Formatting.Indented);
blob.UploadText(json);
}
else
{
blob = _imagesContainer.GetBlockBlobReference(relativePath);
var image = item as Image;
// Ensure position is reset so upload occurs successfully
image.StreamToUpload.Seek(0, SeekOrigin.Begin);
blob.UploadFromStream(image.StreamToUpload);
}
else
{
blob = _jsonContainer.GetBlockBlobReference(relativePath);
var json = JsonConvert.SerializeObject(item, Formatting.Indented);
blob.UploadText(json);
}
}

public void Delete<TEntity>(object key) where TEntity : class, new()
{
string relativePath = GetItemPath<TEntity>(key.ToString());
ICloudBlob blob = null;
if (typeof(TEntity).Equals(typeof(Image)))
{
blob = _imagesContainer.GetBlockBlobReference(relativePath);
}
else
{
blob = _jsonContainer.GetBlockBlobReference(relativePath);
}
ICloudBlob blob = GetBlobContainer<TEntity>().GetBlockBlobReference(relativePath);
blob.Delete();
}
}
Expand Down
Loading

0 comments on commit 8578e15

Please sign in to comment.