Understanding Azure File Share

n

nAll of us atnsome point, be in our educational institutes or in professional world have usednthe file share, i.e. the common storage space maintained by IT team of annorganization where users can create their folders, access common softwareninstallers or keep project specific documents. Usually we mount this storagenspace as a network drive for easy and quick access.

n

n

n

n

n

nThis articlendescribes the details of below topics 

n

n

n

    n

  • Basics of Azure file storage
  • n

  • Creation of file storage servicenusing Azure portal
  • n

  • Mounting file share as drive
  • n

  • Accessing file share usingnstorage client libraries.
  • n

  • Setting SAS policies on contentnin file share using storage client libraries.
  • n

n

n

n

nBasics of Azure File Storage

n

n

n

n

nAzure filenstorage is an offering of Microsoft Azure is an equivalent to SMB file share. Thenlegitimate question to be asked here is since I can anyway have SMB file sharenimplementation on premise, why would I go with Azure file storage? And here arenyour reasons

n

n

n

    n

  • You cannquickly migrate legacy applications relying on file share.
  • n

  • Avoid costlynre-writes.
  • n

  • Azure filenstorage becomes your central share which can be consumed by Virtual machinesnrunning in Azure, Cloud services, any on premise clients with SMB protocol.
  • n

  • Betterncontrol and more built in accessibility options available. E.g. System I/OnAPIs, REST API, Client libraries, PowerShell cmdlets.
  • n

  • Easynintegration with Linux.
  • n

  • Betternscalability and performance targets.
  • n

  • Simplifiednhosting for high availability workload data
  • n

n
n

nnnnnnnnnnnnn

n

n

nNote that asnof today, file storage doesn’t support active directory based authenticationnmechanism to validate access requests. Instead it uses access key basednmechanism of storage account. If you need to have more control on stored content,nthen you should use shared access token as an alternative.

n

n

n

nWhat is SMB

n

n

nThe filenshares are typically driven by a protocol called as SMB. SMB protocol is ServernMessage Block, which is nothing but a mechanism to provide shared access tonfiles, printers, and serial ports over the network.

n

n

n

nMicrosoft’snimplementation of this protocol is called as Microsoft SMB. It was introducednwith Windows vista operating system as SMB 2.0 and revisions of the same werenmade later in Windows 7 with subsequent major revisions of 2.1 and 3.0 as of today.

n

n

n

nConcept of Azure File Storage

n

nLet’s try tonunderstand the concept of Azure file storage

n

n

n

nStorage Account

n

nBasically itnis a subset of azure storage services and hence we will need an azure storagenaccount.  

n

n

n

nShare

n

nShares cannbe considered as logical representations of the drives which you can map. It isna container of directories and you can create unlimited number of shares withinna storage account and each share can store maximum of 5 TBs of data.

n

n

n

nDirectory

n

nThese arennothing but the folders you can create within a file share. It is an optionalnentity in the hierarchy.

n

n

n

nFile

n

nYou cannstore any number and any type of files in a file share. Each share has itsnquota limit and can be maxed up to 5 TBs. Maximum file size than can be storednis 1TB.

n

n

n

n

n

nThenhierarchy can be visualized as below

n

n

n

n

n

n

n

n
n

nnnnnnnnn

n

n

n

nAs shown innthe image above, storage account contains two file shares. i.e. Share 1 andnShare 2. Each share has two directories and each directory is containing somenfiles.

n

n

n

nThe Url ofnthe file stored within a directory or in a share is formed in a followingnformat

n

n

n

nhttps://<storage account>.file.core.windows.net/<share>/<directory/directories>/<file>

n

n

n

n

n

nFail-over and Backup

n

n

n

nFor anynstorage solutions, one of the key criteria is to make sure that data is notnlost even in disaster. File share being an azure storage offering, it doesnfollow all disaster recovery and failover standards and mechanisms as ofnstorage account however there is slight difference. What is it?

n

nAs ofnwriting this article, the file share witness and RA-GRS (Read Access – GeonRedundant Storage) is not supported for file share.

n

n

n

n

n

nAbout backnup, though there is no official way to back up the azure file share there isnalways a workaround. You can automate the process of backup with the help of AzCopy and backup your file share content to blob storage or installnback up agents like Cobian to set up your full and incremental back upnprocedures of file share mapped drive.

n

n

n

nCreating File Share using Azure Portal

n

n

nLet’s gonahead and set up and azure file share using azure portal. It is a quitenstraightforward process and starts with creation of a storage account.

n

n

n

nLet’s createna storage account with name demofsstorageaccountnwithin a resource group which I created earlier. You can choose to creatennew resource group if you don’t have one. Once you are done filling allnrequired information, hit create button and it will submit the creation job tonazure.

n

n

n

nAs this is andemo storage account, I have set its type as locally redundant. To Read morenabout what all types you can select and what their significances are, it isnrecommended that you should go through this link at least once.

n

n

n

n

n

n

n

n

n

n

nOnce thenstorage account gets created, browse to it and click on the Files section asnselected in image below

n

n

n

n

n

n

n

n

n

nClick on thenAdd file share button at the top of the File service panel. It will open upnanother panel where you can give name to the file share and declare its quota.

n

n

n

n

n

nLet’s givenfile share name as “sharedfiles” andnquota limit as 1 GB, it immediately creates the share for you which looks likenbelow

n

n

n

n

n

n

n

n

n

nTake a notenof the highlighted buttons which are quite self-explanatory. We will take andetailed look at connect button later in this article.

n

n

n

nBefore wenadd some files, let’s add a directory in file share and which will act asnfolder for our files. Name it as “SharednContent

n

n

n

n

n

nClick on thenupload button and it opens up a panel with typical file upload control with multiplenselection enabled. You can browse files that needs go on file share and selectnstart upload button in header of the panel. We can see that directory and filesnare being shown in the file share now.

n

n

n

n

n

n

n

n

n

nSelect anynfile and click on properties button in the header. You will be shown URL of thenfile which follows the same format as mentioned above in this article

n

n

n

n

n

n

n

n

n

nNote thatnthere is ETAG associated with each file meaning that the files will be cachedndepending on the change in contents of the file. The cached copy of thendocument will be sent down to client every time when it is requested.

n

n

n

n

n

nLet’s try tonupdate our excel file by deleting it from share and uploading a new copy withnsame name. Observe the change in the ETAG

n

n

n

n

n

n

n

n

n

nMapping File Share as Network Drive

n

n

n

nAs mentionednbefore, we can map the file share as network drive so that content on itnbecomes easily accessible and you can browse through different directoriesnquickly.

n

nIt is quitenstraightforward process and I am sure many of you might have done it alreadynbut even if you haven’t, here are simple steps to do it.

n

nBeforenwe go ahead and map it as local drive, there are certain things you need to benaware of

n

n

n

    n

  • The clientndevice should support SMB 3.0nprotocol (Windows 8 and above OS) and portn445 (TCP outbound) is open.
  • n

  • If younmapping drive on windows virtual machine hosted on azure in a same subscriptionnand same region as of your file share service then the traffic between Azure VMnand file share will be free, else you would be charged for the traffic asnexternal bandwidth.
  • n

  • For Windows 7 devices, though they supportnSMB 2.1 but access from outside of azure is restricted due to lack of channelnencryption in SMB 2.1, however SMB 2.1 is supported if you are accessing thenshare within Azure.
  • n

n
n

n

n

n

n

nMapping cannbe done in multiple ways, one is using command prompt and other is using UI onnwindows devices.

n

n

n

nRemember thenConnect button mentioned above in this article? it shows simple instructionsnhow you can map your file share as network drive using command prompt.

n

nOpen “MynComputer” (Quickest way to launch it Windows key + “E”) and select the optionnfrom the top action links which says Map Network Drive.

n

nName thendrive and enter path of the file share which we just created.

n

n

n

n

nSince Azurenfile share doesn’t support any other authentication mechanism than typicalnstorage key as of now, select both checkboxes i.e re-connect on logon andnconnect using different credentials.

n

n

n

n

n

nOnce you arendone, you will be asked for credentials. Makensure you enter your storage account credentials in the authenticationndialog. You can get the primary or secondary storage key of your account innstorage account Settings > Access keys.

n

n

n

n

n

n

n

n

n

n

n

n

n

n

n

nAfternsuccessful authentication, you should be able to see the mapped drive in yournexplorer.

n

n

n

n

n

n

n

n

n

nAccessing File Share using Client Libraries

n

n

n

nBefore wenstart this, make sure that you are using 5.x + version of storage clientnassemblies. Also note that Azure emulator currently do not support File sharenso make sure that you are pointing to correct file share service on azure.

n

n

n

nLet’s createna console application which will access and download the files in a file sharenwhich we have recently created. Create new console application project innvisual studio and install “WindowsAzure.Storagen-Version 6.2.0” nugget on it.

n

nThe samplencode to access and download the file is as below

n

n

n

nNote – Thencode below is just for the demo purpose and may not be the best performingncode.

n

n

n

nIt connectsnto the file share and verifies if it exists and then proceeds, same is done forngetting connected to directory and file to be downloaded. It downloads the filento the local file system.

n

n

n

n

n

nNote that itnreads the connection string of the storage account from the applicationnconfiguration file so to run the code below as-is, you will need to add the keynwith same name to your app.config and set it’s value to connection string ofnyour storage account (which can be easily found on azure portal by going in thenSettings > Access Keys)

n

n

n

n

n

n

nclass Program

n

n{

n

n   static void Main(string[] args)

n

n  n{

n

n    ntry

n

n    n{

n

n      nCloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings[“StorageAccountConnectionString”]);

n

n      nCloudFileClient fileClient =nstorageAccount.CreateCloudFileClient();

n

n

n

n      nCloudFileShare fileShare =nfileClient.GetShareReference(sharedfiles);

n

n      nif (fileShare.Exists())

n

n      n{

n

n        nCloudFileDirectory rootDirectory =nfileShare.GetRootDirectoryReference();

n

n        nif (rootDirectory.Exists())

n

n        n{

n

n          nCloudFileDirectory customDirectory =nrootDirectory.GetDirectoryReference(Shared Content);

n

n          nif (customDirectory.Exists())

n

n          n{

n

n             CloudFile file = customDirectory.GetFileReference(The Word.docx);

n

n             if (file.Exists())

n

n             {

n

n               Console.WriteLine(“Downloading file..”);

n

n               DownloadFileFromShare(file, @”D:\Downloaded_The_Word.docx);

n

n             }

n

n          n}

n

n         n}

n

n       n}

n

n     n}

n

n     ncatch (Exception ex)

n

n     n{

n

n        nConsole.WriteLine(“Error: “ + ex.Message);

n

n     n}

n

n     nfinally

n

n     n{

n

n         nConsole.WriteLine(“Enter to exit..”);

n

n         nConsole.ReadLine();

n

n     n}

n

n   n}

n

n

n

n   nprivate static async void DownloadFileFromShare(CloudFile file, string saveToPath)

n

n   n{

n

n      nawaitnfile.DownloadToFileAsync(saveToPath, System.IO.FileMode.OpenOrCreate);

n

n   n}

n

n

n

n

na

n

n

n

n

n

nSetting SAS policies on content in file share

n

n

n

nAs mentionednin the article above, we can set up SAS policies using storage client librariesnfor better control over the content, let’s see how it can be done.

n

nThis articlenassumes that users have basic understanding of SAS and related policies and sonwill only focus on setting these policies on file share contents. If you do notnknow about SAS, you can read more information here.

n

n

n

nThe basicnidea is, when you don’t trust your storage clients and still you want tonprovide access to resources in storage then you can achieve this by providingnshared access signature token and let clients access the resource for limitednperiod. You can optionally define the access policy and generate token from thenpolicy which we will do in our example below. The benefit you get out of thisnis, you don’t have to share the primary or secondary key of your storagenaccount to the end users which ultimately provides them the administrativenaccess to your storage account.

n

n

n

nIn ournsample code below what we will do is, we will define a SAS policy with readnonly permissions on the file share which we created. We will try to perform thenwrite operation on file share i.e. by creating a new file in file share, it isnexpected that the code should run with an error as we don’t have any writenpermissions yet.

n

n

n

nIf we runncode below as-is then we should get error like this

n

n

n

n

n

n

n

n

n

n

n

n

n

n

nclass Program

n

n   n{

n

n       nstatic void Main(string[] args)

n

n       n{

n

n            try

n

n            {

n

n                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings[“StorageAccountConnectionString”]);

n

n                CloudFileClient fileClient =nstorageAccount.CreateCloudFileClient();

n

n

n

n                CloudFileShare fileShare =nfileClient.GetShareReference(“sharedfiles”);

n

n                if (fileShare.Exists())

n

n                {

n

n                    string policyName = “DemoPolicy” + new Random().Next(50);

n

n

n

n                    FileSharePermissions fileSharePermissions =nfileShare.GetPermissions();

n

n                   

n

n                    // define policy

n

n                    SharedAccessFilePolicy sharedAccessFilePolicy = new SharedAccessFilePolicy()

n

n                    {

n

n                        SharedAccessExpiryTimen= DateTime.UtcNow.AddHours(1),

n

n                        Permissions = SharedAccessFilePermissions.Read

n

n                        //Permissions =nSharedAccessFilePermissions.Write

n

n                    };

n

n

n

n                   nfileSharePermissions.SharedAccessPolicies.Add(policyName,nsharedAccessFilePolicy);

n

n

n

n                    // set permissions of filenshare

n

n                    fileShare.SetPermissions(fileSharePermissions);

n

n

n

n                    // generate SAS token basednon policy and use to create a new file

n

n                    CloudFileDirectory rootDirectory =nfileShare.GetRootDirectoryReference();

n

n                    if (rootDirectory.Exists())

n

n                    {

n

n                        CloudFileDirectory customDirectory =nrootDirectory.GetDirectoryReference(“Shared Content”);

n

n                        if (customDirectory.Exists())

n

n                        {

n

n                            CloudFile file = customDirectory.GetFileReference(“DemoFile.txt”);

n

n                            string sasToken =nfile.GetSharedAccessSignature(null, policyName);

n

n

n

n                            //generate URL of file withnSAS token

n

n                            Uri fileSASUrl = new Uri(file.StorageUri.PrimaryUri.ToString()n+ sasToken);

n

n                            CloudFile newFile = new CloudFile(fileSASUrl);

n

n                            newFile.UploadText(“Hello!”);

n

n                        }

n

n                    }

n

n                }

n

n

n

n            }

n

n

n

n            catchn(Exception ex)

n

n            {

n

n                Console.WriteLine(“Error: “ + ex.Message);

n

n            }

n

n            finally

n

n            {

n

n                Console.WriteLine(“Enter to exit..”);

n

n                Console.ReadLine();

n

n            }

n

n

n

n       n}

n

n   n}

n

n

n

n

nNow we will simply change the permission of the policynand let users give permissions to write and run the code.

n

n

n

n

n

nNote that the change in is only in a line i.e.

n

n

n

n

n// define policy

n

n  SharedAccessFilePolicy sharedAccessFilePolicy = new SharedAccessFilePolicy()

n

n  {

n

n   nSharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),

n

n   nPermissions = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write

n

n n};

n

n

n

n

n

n

nCode runs successfully, let’s verify if file got creatednin file share.

n

n

n

n

n

n

n

n

n

nIf you download the file and see the content, you shouldnbe able to see Hello! Which we wrote using our console application.

n

nThere are lots of other possibilities to configure andnplay around the file share using the client storage assemblies and PowerShellnscripts.

n

n

n

n

n

nThanks for reading this and your views, comments will benappreciated.

n

Leave a Comment