Azure Blob和表存储以更简单的方式重写代码

时间:2018-12-18 10:45:45

标签: c# dependency-injection azure-storage azure-storage-blobs azure-table-storage

我写了这段代码,但是不是很实用。我在这个编码领域还是新手。基本上,我将图像存储到Blob容器中,并将URL保存在表中。我正在为文本文件做同样的事情。 因此,我想对蓝色连接部分使用依赖注入,以使我的代码更实用。

这是我的徽标控制器。

[Route("api/manage/logo")]
[ApiController]

public class ManageLogoController : ControllerBase
{

    [HttpPost("{version}")]
    public async Task<IActionResult> Post(IFormFile image, float version)
    {
        if (image.Length >= 1048576)
        {
            return BadRequest("Uploaded image may not exceed 1Mb, please upload a smaller image.");
        }

        var allowedExtensions = new[] {
            ".png", ".jpg", "jpeg" };
        string fileExt = Path.GetExtension(image.FileName);
        if (allowedExtensions.Contains(fileExt))
        {
            try
            {
                await LogoStorage.UploadFileToBlobStorage(version, image.FileName);
                return Ok(new
                {
                    lenght = image.Length,
                    name = image.FileName
                });
            }
            catch (Exception ex)
            {
                return BadRequest();
            }
        }

TnC控制器

[Route("api/manage/tnc")]
[ApiController]

public class ManageTermCondController : ControllerBase
{

[HttpPost("{version}")]
public async Task<IActionResult> Post(IFormFile doc, float version)
{

    var allowedExtension = ".txt";
    string fileExt = Path.GetExtension(doc.FileName);
    if (allowedExtension.Contains(fileExt))
    {
        try
        {
            await TncStorage.UploadDocToBlobStorage(version, doc.FileName);
            return Ok(new
            {
                lenght = doc.Length,
                name = doc.FileName
            });
        }
        catch (Exception ex)
        {
            return BadRequest();
        }
    }

    else
    {
        return BadRequest("Only .txt files are allowed!");
    }
}



[HttpGet]
public string Geti(float version)
{
    var x = TncStorage.GetURL(version);
    if (x == null)
    {
        return "There's no such record";
    }
    else return TncStorage.GetURL(version);

}
}

接下来的部分中,我创建了一个名为.Service的新类库。

 public class VersionURL : TableEntity
        {
            public VersionURL(string type, string version)
            {
                PartitionKey = type;
                RowKey = version;
            }
            public VersionURL() { }
            public string URL { get; set; }
            public string ETag { get; set; }


    }

头等舱。

public static async Task UploadFileToBlobStorage(float version, string filename)
{
    CloudStorageAccount storageAccount = null;
    CloudBlobContainer cloudBlobContainer = null;
    string storageConnectionString = "";

    if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
    {
        try
        {

            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            cloudBlobContainer = cloudBlobClient.GetContainerReference("logodata");
            await cloudBlobContainer.CreateIfNotExistsAsync();
            BlobContainerPermissions permissions = new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            };
            await cloudBlobContainer.SetPermissionsAsync(permissions);

            var blobUrl = "";
            string file = Guid.NewGuid().ToString() + Path.GetExtension(filename);
            CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(file);
            try
            {
                await cloudBlockBlob.UploadFromFileAsync(filename);

            }
            catch (Exception ex)
            {

            }
            blobUrl = cloudBlockBlob.Uri.AbsoluteUri;


            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("CommonURL");
            await table.CreateIfNotExistsAsync();

            var v = "v" + version;
            VersionURL content = new VersionURL("Logo", v);
            content.ETag = "*";
            content.URL = blobUrl;
            var query = new TableQuery<VersionURL>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, v));
            TableContinuationToken continuationToken = null;
            do
            {
                var result = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
                continuationToken = result.ContinuationToken;

                if (result.Count() != 0)
                {
                    foreach (VersionURL entity in result)
                    {
                        if (entity.RowKey == v)
                        {
                            try
                            {
                                TableOperation updateOperation = TableOperation.Merge(content);
                                await table.ExecuteAsync(updateOperation);
                            }
                            catch (Exception ex)
                            {

                            }
                        }

                    }
                }
                else
                {
                    TableOperation insertOperation = TableOperation.Insert(content);
                    await table.ExecuteAsync(insertOperation);
                }
            } while (continuationToken != null);
        }
        catch (StorageException ex)
        {
            Console.WriteLine("Error returned from the service: {0}", ex.Message);
        }
        finally
        {

        }
    }
    else
    {
        Console.WriteLine(
            "A connection string has not been defined in the system environment variables. " +
            "Add a environment variable named 'storageconnectionstring' with your storage " +
            "connection string as a value.");
    }
}
    }

第二堂课。

  public class TncStorage
    {

public static async Task UploadDocToBlobStorage(float version, string filename)
{
    CloudStorageAccount storageAccount = null;
    CloudBlobContainer cloudBlobContainer = null;
    string storageConnectionString = "";

    if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
    {
        try
        {

            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            cloudBlobContainer = cloudBlobClient.GetContainerReference("tncdata");
            await cloudBlobContainer.CreateIfNotExistsAsync();
            BlobContainerPermissions permissions = new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            };
            await cloudBlobContainer.SetPermissionsAsync(permissions);

            var blobUrl = "";
            string file = Guid.NewGuid().ToString() + Path.GetExtension(filename);
            CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(file);
            try
            {
                await cloudBlockBlob.UploadFromFileAsync(filename);

            }
            catch (Exception ex)
            {

            }
            blobUrl = cloudBlockBlob.Uri.AbsoluteUri;


            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("CommonURL");
            await table.CreateIfNotExistsAsync();
            var v = "v" + version;
            VersionURL content = new VersionURL("TnC", v);
            content.ETag = "*";
            content.URL = blobUrl;
            var query = new TableQuery<VersionURL>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, v));
            TableContinuationToken continuationToken = null;
            do
            {
                var result = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
                continuationToken = result.ContinuationToken;

                if (result.Count() != 0)
                {
                    foreach (VersionURL entity in result)
                    {
                        if (entity.RowKey == v)
                        {
                            try
                            {

                                var dec = version + .1;
                                content.RowKey = "v" + dec;
                                TableOperation updateOperation = TableOperation.Insert(content);
                                await table.ExecuteAsync(updateOperation);


                            }
                            catch (Exception ex)
                            {

                            }
                        }

                    }
                }
                else
                {
                    TableOperation insertOperation = TableOperation.Insert(content);
                    await table.ExecuteAsync(insertOperation);
                }
            } while (continuationToken != null);
        }
        catch (StorageException ex)
        {
            Console.WriteLine("Error returned from the service: {0}", ex.Message);
        }
        finally
        {

        }
    }
    else
    {
        Console.WriteLine(
            "A connection string has not been defined in the system environment variables. " +
            "Add a environment variable named 'storageconnectionstring' with your storage " +
            "connection string as a value.");
    }
}


public static string GetURL(float version)
{
    CloudStorageAccount storageAccount = null;
    string storageConnectionString = "";
    storageAccount = CloudStorageAccount.Parse(storageConnectionString);
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
    CloudTable table = tableClient.GetTableReference("CommonURL");
    var v = "v" + version;
    var tableQuery = new TableQuery<VersionURL>();
    tableQuery = new TableQuery<VersionURL>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, v));
    var entities = table.ExecuteQuerySegmentedAsync(tableQuery, null);
    var results = entities.Result;
    var s = "";
    foreach (var file in results.Where(x => x.RowKey == v))
    {
        //if (file.RowKey == v)
        //{
        return s = file.URL;

        //}
        //else
        //    return null;
    }

    return null;
}

我可以简化第一和第二节课吗?

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,请假设您想通过重用一些通用函数来简化这两个类。

您可以创建另一个类(例如名为Common.cs的类),并将所有可重复使用的代码放在此处。

演示在这里,如果我误会了,请纠正我:

Common.cs:

    public class Common
    {
        //get the storage account
        public static CloudStorageAccount GetStorageAccount(string storageConnectionString)
        {
            CloudStorageAccount storageAccount = null;
            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                return storageAccount;
            }
            else
            {
                Console.WriteLine(
                    "A connection string has not been defined in the system environment variables. " +
                    "Add a environment variable named 'storageconnectionstring' with your storage " +
                    "connection string as a value.");
            }

            return null;
        }

        //get the blob url
        public static async Task<string> GetBlobUrl(CloudStorageAccount storageAccount,string BlobContainerName,string filename)
        {
            try
            {

                CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("tncdata");
                await cloudBlobContainer.CreateIfNotExistsAsync();
                BlobContainerPermissions permissions = new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                };
                await cloudBlobContainer.SetPermissionsAsync(permissions);

                var blobUrl = "";
                string file = Guid.NewGuid().ToString() + Path.GetExtension(filename);
                CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(file);
                try
                {
                    await cloudBlockBlob.UploadFromFileAsync(filename);

                }
                catch (Exception ex)
                {

                }
                blobUrl = cloudBlockBlob.Uri.AbsoluteUri;
                return blobUrl;
            }
            catch (StorageException ex)
            {
                Console.WriteLine("Error returned from the service: {0}", ex.Message);
            }
            finally
            {

            }

            return null;
        }

        //get or create table async
        public static async Task<CloudTable> GetTableAsnyc(CloudStorageAccount storageAccount,string tablename)
        {
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("CommonURL");
            await table.CreateIfNotExistsAsync();

            return table;
        }

        //get or create table
        public static CloudTable GetTable(CloudStorageAccount storageAccount, string tablename)
        {
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable table = tableClient.GetTableReference(tablename);

            return table;
        }

    }

然后在头等舱:

    public class FirstClass
    {
        public static async Task UploadFileToBlobStorage(float version, string filename)
        {
            string storageConnectionString = "";
            CloudStorageAccount storageAccount = Common.GetStorageAccount(storageConnectionString);

            string blobUrl = await Common.GetBlobUrl(storageAccount, "logodata", filename);

            CloudTable table = await Common.GetTableAsnyc(storageAccount, "CommonURL");

            var v = "v" + version;
            VersionURL content = new VersionURL("Logo", v);
            content.ETag = "*";
            content.URL = blobUrl;
            var query = new TableQuery<VersionURL>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, v));
            TableContinuationToken continuationToken = null;
            do
            {
                var result = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
                continuationToken = result.ContinuationToken;

                if (result.Count() != 0)
                {
                    foreach (VersionURL entity in result)
                    {
                        if (entity.RowKey == v)
                        {
                            try
                            {
                                TableOperation updateOperation = TableOperation.Merge(content);
                                await table.ExecuteAsync(updateOperation);
                            }
                            catch (Exception ex)
                            {

                            }
                        }

                    }
                }
                else
                {
                    TableOperation insertOperation = TableOperation.Insert(content);
                    await table.ExecuteAsync(insertOperation);
                }
            } while (continuationToken != null);

        }
    }

第二堂课

    public class SecondClass
    {
        public static async Task UploadDocToBlobStorage(float version, string filename)
        {
            string storageConnectionString = "";
            CloudStorageAccount storageAccount = Common.GetStorageAccount(storageConnectionString);

            string blobUrl = await Common.GetBlobUrl(storageAccount, "tncdata", filename);

            CloudTable table = await Common.GetTableAsnyc(storageAccount, "CommonURL");

            var v = "v" + version;
            VersionURL content = new VersionURL("TnC", v);
            content.ETag = "*";
            content.URL = blobUrl;
            var query = new TableQuery<VersionURL>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, v));
            TableContinuationToken continuationToken = null;
            do
            {
                var result = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
                continuationToken = result.ContinuationToken;

                if (result.Count() != 0)
                {
                    foreach (VersionURL entity in result)
                    {
                        if (entity.RowKey == v)
                        {
                            try
                            {

                                var dec = version + .1;
                                content.RowKey = "v" + dec;
                                TableOperation updateOperation = TableOperation.Insert(content);
                                await table.ExecuteAsync(updateOperation);


                            }
                            catch (Exception ex)
                            {

                            }
                        }

                    }
                }
                else
                {
                    TableOperation insertOperation = TableOperation.Insert(content);
                    await table.ExecuteAsync(insertOperation);
                }
            } while (continuationToken != null);

        }


        public static string GetURL(float version)
        {

            string storageConnectionString = "";
            CloudStorageAccount storageAccount = Common.GetStorageAccount(storageConnectionString);
            CloudTable table = Common.GetTable(storageAccount, "CommonURL");

            var v = "v" + version;
            var tableQuery = new TableQuery<VersionURL>();
            tableQuery = new TableQuery<VersionURL>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, v));
            var entities = table.ExecuteQuerySegmentedAsync(tableQuery, null);
            var results = entities.Result;
            var s = "";
            foreach (var file in results.Where(x => x.RowKey == v))
            {
                //if (file.RowKey == v)
                //{
                return s = file.URL;

                //}
                //else
                //    return null;
            }

            return null;
        }

    }