Running the sample

Please follow the steps below.

Step 1: Open the CSAzureServeFilesFromBlobStorage.sln as Administrator. Expand the CSAzureServeFilesFromBlobStorage application and set CSAzureServeFilesFromBlobStorage azure application as the startup project, press F5 to display Default.aspx page.

Step 2: Please add your Windows Azure Storage Account and Key in the Windows Azure settings, "StorageConnections". If you do not have one, please use Windows Azure Storage Emulator.  You will see a web page with two unavailable links on it. Please click the link "Add default resources page" to redirect to default resources adding page.

Step 3:  Click the "Click to upload the default resources" button to upload your resources to Windows Azure Blob Storage and Table Storage. You can find "Microsoft.jpg, MSDN.jpg and Site.css" in the "Files" folder. These files will be uploaded to the blob container and their information will be stored in table storage.

Step 4: The files have been uploaded now. You can go to Microsoft Windows Azure Management Portal or use Azure Storage Explore tool to view your resources. The default blob container name is "container" and default table name is "files".

Step 5: Go back to the Default.aspx page. You will find the uploaded resources appear on it. Click the link to view them.

Step 6: In this sample, you can access jpg and css files (also including .aspx files). Files of other types, such as .htm files, cannot be reached.

Step 7: Validation finished.

Using the Code

Step 1. Create a C# "Windows Azure Project" in Visual Studio 2012. Name it as "CSAzureServeFilesFromBlobStorage". Add a Web Role and name it as "ServeFilesFromBlobStorageWebRole"; add a class library and name it as "TableStorageManager". Make sure the class library's target framework is .NET Framework 4.5 (Not .NET Framework 4.5 Client Profile).

Step 2. Add 3 class files in TableStorageManager class library, which is used to package the bottom table storage methods. Try to add Windows Azure references and Data Service client reference.

Microsoft.WindowsAzure.Diagonostics

Microsoft.WindowsAzure.ServiceRuntime

Microsoft.WindowsAzure.StorageClient

System.Data.Service.Client

The FileEntity class is a table storage entity class; it includes some basic properties. The FileContext class is used to create queries for table services. You can also add paging method for table storage. The FileDataSource package the bottom layer methods (about cloud account, TableServiceContext, credentials, etc)

C#

Edit|Remove

csharp

public class FileDataSource

{

private static CloudStorageAccount account;

private FileContext context;

public FileDataSource()

{

// Create table storage client via cloud account.

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

CloudTableClient client = account.CreateCloudTableClient();

client.CreateTableIfNotExist("files");

// Table context properties.

context = new FileContext(account.TableEndpoint.AbsoluteUri, account.Credentials);

context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));

context.IgnoreResourceNotFoundException = true;

context.IgnoreMissingProperties = true;

}

/// <summary>

/// Get all entities method.

/// </summary>

/// <returns></returns>

public IEnumerable<FileEntity> GetAllEntities()

{

var list = from m in this.context.GetEntities

select m;

return list;

}

/// <summary>

/// Get table rows by partitionKey.

/// </summary>

/// <param name="partitionKey"></param>

/// <returns></returns>

public IEnumerable<FileEntity> GetEntities(string partitionKey)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey

select m;

return list;

}

/// <summary>

/// Get specify entity.

/// </summary>

/// <param name="partitionKey"></param>

/// <param name="fileName"></param>

/// <returns></returns>

public FileEntity GetEntitiesByName(string partitionKey, string fileName)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey && m.FileName == fileName

select m;

if (list.Count() > 0)

return list.First<FileEntity>();

else

return null;

}

/// <summary>

/// Add an entity.

/// </summary>

/// <param name="entity"></param>

public void AddFile(FileEntity entity)

{

this.context.AddObject("files", entity);

this.context.SaveChanges();

}

/// <summary>

/// Make a judgment to check if file is exists.

/// </summary>

/// <param name="filename"></param>

/// <param name="partitionKey"></param>

/// <returns></returns>

public bool FileExists(string filename, string partitionKey)

{

IEnumerable<FileEntity> list = from m in this.context.GetEntities

where m.FileName == filename && m.PartitionKey == partitionKey

select m;

if (list.Count()>0)

{

return true;

}

else

{

return false;

}

}

}

public class FileDataSource

{

private static CloudStorageAccount account;

private FileContext context;

public FileDataSource()

{

// Create table storage client via cloud account.

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

CloudTableClient client = account.CreateCloudTableClient();

client.CreateTableIfNotExist("files");

// Table context properties.

context = new FileContext(account.TableEndpoint.AbsoluteUri, account.Credentials);

context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));

context.IgnoreResourceNotFoundException = true;

context.IgnoreMissingProperties = true;

}

/// <summary>

/// Get all entities method.

/// </summary>

/// <returns></returns>

public IEnumerable<FileEntity> GetAllEntities()

{

var list = from m in this.context.GetEntities

select m;

return list;

}

/// <summary>

/// Get table rows by partitionKey.

/// </summary>

/// <param name="partitionKey"></param>

/// <returns></returns>

public IEnumerable<FileEntity> GetEntities(string partitionKey)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey

select m;

return list;

}

/// <summary>

/// Get specify entity.

/// </summary>

/// <param name="partitionKey"></param>

/// <param name="fileName"></param>

/// <returns></returns>

public FileEntity GetEntitiesByName(string partitionKey, string fileName)

{

var list = from m in this.context.GetEntities

where m.PartitionKey == partitionKey && m.FileName == fileName

select m;

if (list.Count() > 0)

return list.First<FileEntity>();

else

return null;

}

/// <summary>

/// Add an entity.

/// </summary>

/// <param name="entity"></param>

public void AddFile(FileEntity entity)

{

this.context.AddObject("files", entity);

this.context.SaveChanges();

}

/// <summary>

/// Make a judgment to check if file is exists.

/// </summary>

/// <param name="filename"></param>

/// <param name="partitionKey"></param>

/// <returns></returns>

public bool FileExists(string filename, string partitionKey)

{

IEnumerable<FileEntity> list = from m in this.context.GetEntities

where m.FileName == filename && m.PartitionKey == partitionKey

select m;

if (list.Count()>0)

{

return true;

}

else

{

return false;

}

}

}

Step 3. Then we need add a class in ServeFilesFromBlobStorageWebRole project as an HttpModuler to check the types of requested files and access the files in Blob Storage.

C#

Edit|Remove

csharp

public void Init(HttpApplication context)

{

context.BeginRequest += new EventHandler(this.Application_BeginRequest);

}

/// <summary>

/// Check file types and request it by cloud blob API.

/// </summary>

/// <param name="source"></param>

/// <param name="e"></param>

private void Application_BeginRequest(Object source,EventArgs e)

{

string url = HttpContext.Current.Request.Url.ToString();

string fileName = url.Substring(url.LastIndexOf('/') + 1).ToString();

string extensionName = string.Empty;

if (fileName.Substring(fileName.LastIndexOf('.') + 1).ToString().Equals("aspx"))

{

return;

}

if (!fileName.Equals(string.Empty))

{

extensionName = fileName.Substring(fileName.LastIndexOf('.') + 1).ToString();

if (!extensionName.Equals(string.Empty))

{

string contentType = this.GetContentType(fileName);

if (contentType.Equals(string.Empty))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

};

{

FileDataSource dataSource = new FileDataSource();

string paritionKey = this.GetPartitionName(extensionName);

if (String.IsNullOrEmpty(paritionKey))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

}

FileEntity entity = dataSource.GetEntitiesByName(paritionKey, "Files/" + fileName);

if (entity != null)

HttpContext.Current.Response.Redirect(entity.FileUrl);

else

HttpContext.Current.Server.Transfer("NoResources.aspx");

}

}

}

}

/// <summary>

/// Get file's Content-Type.

/// </summary>

/// <param name="filename"></param>

/// <returns></returns>

public string GetContentType(string filename)

{

string res = string.Empty;

switch (filename.Substring(filename.LastIndexOf('.') + 1).ToString().ToLower())

{

case "jpg":

res = "image/jpg";

break;

case "css":

res = "text/css";

break;

}

return res;

}

/// <summary>

/// Get file's partitionKey.

/// </summary>

/// <param name="extensionName"></param>

/// <returns></returns>

public string GetPartitionName(string extensionName)

{

string partitionName = string.Empty;

switch(extensionName)

{

case "jpg":

partitionName = "image";

break;

case "css":

partitionName = "css";

break;

}

return partitionName;

}

public void Init(HttpApplication context)

{

context.BeginRequest += new EventHandler(this.Application_BeginRequest);

}

/// <summary>

/// Check file types and request it by cloud blob API.

/// </summary>

/// <param name="source"></param>

/// <param name="e"></param>

private void Application_BeginRequest(Object source,EventArgs e)

{

string url = HttpContext.Current.Request.Url.ToString();

string fileName = url.Substring(url.LastIndexOf('/') + 1).ToString();

string extensionName = string.Empty;

if (fileName.Substring(fileName.LastIndexOf('.') + 1).ToString().Equals("aspx"))

{

return;

}

if (!fileName.Equals(string.Empty))

{

extensionName = fileName.Substring(fileName.LastIndexOf('.') + 1).ToString();

if (!extensionName.Equals(string.Empty))

{

string contentType = this.GetContentType(fileName);

if (contentType.Equals(string.Empty))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

};

{

FileDataSource dataSource = new FileDataSource();

string paritionKey = this.GetPartitionName(extensionName);

if (String.IsNullOrEmpty(paritionKey))

{

HttpContext.Current.Server.Transfer("NoHandler.aspx");

}

FileEntity entity = dataSource.GetEntitiesByName(paritionKey, "Files/" + fileName);

if (entity != null)

HttpContext.Current.Response.Redirect(entity.FileUrl);

else

HttpContext.Current.Server.Transfer("NoResources.aspx");

}

}

}

}

/// <summary>

/// Get file's Content-Type.

/// </summary>

/// <param name="filename"></param>

/// <returns></returns>

public string GetContentType(string filename)

{

string res = string.Empty;

switch (filename.Substring(filename.LastIndexOf('.') + 1).ToString().ToLower())

{

case "jpg":

res = "image/jpg";

break;

case "css":

res = "text/css";

break;

}

return res;

}

/// <summary>

/// Get file's partitionKey.

/// </summary>

/// <param name="extensionName"></param>

/// <returns></returns>

public string GetPartitionName(string extensionName)

{

string partitionName = string.Empty;

switch(extensionName)

{

case "jpg":

partitionName = "image";

break;

case "css":

partitionName = "css";

break;

}

return partitionName;

}

Step 4. Add a Default web page to show links of some examples, and add a FileUploadPage to upload some default resources to Storage for testing.

C#

Edit|Remove

csharp

public partial class FileUploadPage : System.Web.UI.Page

{

private static CloudStorageAccount account;

public List<FileEntity> files = new List<FileEntity>();

protected void Page_Load(object sender, EventArgs e)

{

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

}

/// <summary>

/// Upload existing resources. ("Files" folder)

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void btnUpload_Click(object sender, EventArgs e)

{

FileDataSource source = new FileDataSource();

List<string> nameList = new List<string>() { "Files/Microsoft.jpg", "Files/MSDN.jpg", "Files/Site.css" };

CloudBlobClient client = account.CreateCloudBlobClient();

CloudBlobContainer container = client.GetContainerReference("container");

container.CreateIfNotExist();

var permission = container.GetPermissions();

permission.PublicAccess = BlobContainerPublicAccessType.Container;

container.SetPermissions(permission);

bool flag = false;

foreach (string name in nameList)

{

if (name.Substring(name.LastIndexOf('.') + 1).Equals("jpg") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "image"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("image");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The image file {0} is uploaded successes.
", name);

}

}

else if (name.Substring(name.LastIndexOf('.') + 1).Equals("css") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "css"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("css");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The css file {0} is uploaded successes.
", name);

}

}

}

if (!flag)

{

lbContent.Text = "You had uploaded these resources";

}

}

protected void LinkButton1_Click(object sender, EventArgs e)

{

Response.Redirect("Default.aspx");

}

}

public partial class FileUploadPage : System.Web.UI.Page

{

private static CloudStorageAccount account;

public List<FileEntity> files = new List<FileEntity>();

protected void Page_Load(object sender, EventArgs e)

{

account = CloudStorageAccount.FromConfigurationSetting("StorageConnections");

}

/// <summary>

/// Upload existing resources. ("Files" folder)

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void btnUpload_Click(object sender, EventArgs e)

{

FileDataSource source = new FileDataSource();

List<string> nameList = new List<string>() { "Files/Microsoft.jpg", "Files/MSDN.jpg", "Files/Site.css" };

CloudBlobClient client = account.CreateCloudBlobClient();

CloudBlobContainer container = client.GetContainerReference("container");

container.CreateIfNotExist();

var permission = container.GetPermissions();

permission.PublicAccess = BlobContainerPublicAccessType.Container;

container.SetPermissions(permission);

bool flag = false;

foreach (string name in nameList)

{

if (name.Substring(name.LastIndexOf('.') + 1).Equals("jpg") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "image"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("image");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The image file {0} is uploaded successes.
", name);

}

}

else if (name.Substring(name.LastIndexOf('.') + 1).Equals("css") && File.Exists(Server.MapPath(name)))

{

if (!source.FileExists(name, "css"))

{

flag = true;

CloudBlob blob = container.GetBlobReference(name);

blob.UploadFile(Server.MapPath(name));

FileEntity entity = new FileEntity("css");

entity.FileName = name;

entity.FileUrl = blob.Uri.ToString();

source.AddFile(entity);

lbContent.Text += String.Format("The css file {0} is uploaded successes.
", name);

}

}

}

if (!flag)

{

lbContent.Text = "You had uploaded these resources";

}

}

protected void LinkButton1_Click(object sender, EventArgs e)

{

Response.Redirect("Default.aspx");

}

}

Step 5. Please add your Windows Azure Storage account name and key in the Azure project. If you do not have one, use Windows Azure Storage Emulator for testing.

Step 6. Build the application and you can debug it.

源码下载

一个使用微软Azure blob实现文件下载功能的实例-附带源文件的更多相关文章

  1. presto访问 Azure blob storage

    当集群使用Azure Blog Storage时,prestoDB无法获取返回结果,在此记录下 如下,hive里面的两个表,一个使用的是本地的hdfs,一个是使用 azure blob storage ...

  2. 微软Azure云主机及blob存储的网络性能测试

    http://www.cnblogs.com/sennly/p/4137024.html 微软Azure云主机及blob存储的网络性能测试 1. 测试目的 本次测试的目的在于对微软Azure的云主机. ...

  3. 阿里云ONS而微软Azure Service Bus体系结构和功能比较

    阿里云ONS而微软Azure Service bus体系结构和功能比较 版权所有所有,转载请注明出处http://blog.csdn.net/yangzhenping.谢谢! 阿里云的开放消息服务: ...

  4. 微软开放技术发布开源 Jenkins 插件以将 Windows Azure Blob 服务用的开作存储库

     发布于 2014-02-10 作者 陈 忠岳 持续集成 (CI) 的历史源远流长, 其宗旨在于软件团队在敏捷环境中不断将他们的工作整合为持续构建.管理 CI 进程的工具已存在一段时间.过去几年中 ...

  5. 使用 Azure Blob Stoage 实现一个静态文件服务器

    什么是Azure Blob Stoage Azure Blob Stoage 是微软Azure的对象存储服务.国内的云一般叫OSS,是一种用来存储非结构化数据的服务,比如音频,视频,图片,文本等等.用 ...

  6. 微软Azure配置中心 App Configuration (二):Feature Flag 功能开关特性

    写在前面 Web服务开发过程中我们经常有这样的需求: 某些功能我必须我修改了配置才启用,比如新用户注册送券等: 某个功能需到特定的时间才启用,过后就失效,比如春节活动等: 某些功能,我想先对10%的用 ...

  7. 【Azure 机器人】微软Azure Bot 编辑器系列(3) : 机器人对话流中加入帮助和取消按钮功能 (The Bot Framework Composer tutorials)

    欢迎来到微软机器人编辑器使用教程,从这里开始,创建一个简单的机器人. 在该系列文章中,每一篇都将通过添加更多的功能来构建机器人.当完成教程中的全部内容后,你将成功的创建一个天气机器人(Weather ...

  8. 欢迎阅读daxnet的新博客:一个基于Microsoft Azure、ASP.NET Core和Docker的博客系统

    2008年11月,我在博客园开通了个人帐号,并在博客园发表了自己的第一篇博客.当然,我写博客也不是从2008年才开始的,在更早时候,也在CSDN和系统分析员协会(之后名为"希赛网" ...

  9. 一个基于Microsoft Azure、ASP.NET Core和Docker的博客系统

    2008年11月,我在博客园开通了个人帐号,并在博客园发表了自己的第一篇博客.当然,我写博客也不是从2008年才开始的,在更早时候,也在CSDN和系统分析员协会(之后名为“希赛网”)个人空间发布过一些 ...

随机推荐

  1. 转载CSDN (MVC WebAPI 三层分布式框架开发)

    前言:SOA(面向服务的架构)是目前企业应用开发过程中普遍采用的技术,基于MVC WebAPI三层分布式框架开发,以此适用于企业信息系统的业务处理,是本文论述的重点.此外,插件技术的应用,富客户端JQ ...

  2. Hibernate逍遥游记-第7章 Hibernate的检索策略和检索方式(<set lazy="false" fetch="join">、left join fetch、FetchMode.JOIN、)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  3. Qt网络通信骨架解析,QtClient QtServer QtSerialPort

    http://blog.csdn.net/Dr_Abel/article/details/52469134#t18

  4. 计算机视觉和人工智能的状态:我们已经走得很远了 The state of Computer Vision and AI: we are really, really far away.

    The picture above is funny. But for me it is also one of those examples that make me sad about the o ...

  5. php命令行用法简介

    Php是一个非常流行的web服务端脚本语言.其实,php不仅仅可以在web服务器中充当重要角色.在命令行一样可以执行. 本文中,笔者为各位介绍下php在命令行中的使用方法. 1.  查看php的版本. ...

  6. Apache httpd + tomcat 简单集群

    集群其实很简单,我们就来说一下httpd+tomcat集群都要注意哪些部分: 首先使用的东西有 apache-tomcat-8.0.32      下载地址: http://tomcat.apache ...

  7. 爬虫技术(六)-- 使用HtmlAgilityPack获取页面链接(附c#代码及插件下载)

    菜鸟HtmlAgilityPack初体验...弱弱的代码... Html Agility Pack是一个开源项目,为网页提供了标准的DOM API和XPath导航.使用WebBrowser和HttpW ...

  8. 1227. Rally Championship

    1227 题意木看懂 是可以停在路上 任何地方 水题一枚 以下条件之一满足就可以 有环(并查集判) 重边 自己到自己的边 最长边大于s(用flod改写下) #include <iostream& ...

  9. WEB前端开发成长指南

    小 编注:相比起网页射击狮,操纵代码的前端攻城狮凭着双手在键盘巴拉巴拉敲出的字符,就能赋予二次元的静态页面生命,各种lovely 的~~fabulous的~~elegant的交互效果,那叫一个锦上添花 ...

  10. [反汇编练习] 160个CrackMe之006

    [反汇编练习] 160个CrackMe之006. 本系列文章的目的是从一个没有任何经验的新手的角度(其实就是我自己),一步步尝试将160个CrackMe全部破解,如果可以,通过任何方式写出一个类似于注 ...