Esempio n. 1
0
        private async Task <CloudFile> BuildCloudFileInstanceFromPathAsync(string defaultFileName, string[] path, bool pathIsDirectory)
        {
            CloudFileDirectory baseDirectory = null;
            bool isPathEmpty = path.Length == 0;

            switch (this.ParameterSetName)
            {
            case Constants.DirectoryParameterSetName:
                baseDirectory = this.Directory;
                break;

            case Constants.ShareNameParameterSetName:
                NamingUtil.ValidateShareName(this.ShareName, false);
                baseDirectory = this.BuildFileShareObjectFromName(this.ShareName).GetRootDirectoryReference();
                break;

            case Constants.ShareParameterSetName:
                baseDirectory = this.Share.GetRootDirectoryReference();
                break;

            default:
                throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName));
            }

            if (isPathEmpty)
            {
                return(baseDirectory.GetFileReference(defaultFileName));
            }

            var directory = baseDirectory.GetDirectoryReferenceByPath(path);

            if (pathIsDirectory)
            {
                return(directory.GetFileReference(defaultFileName));
            }

            bool directoryExists;

            try
            {
                directoryExists = await this.Channel.DirectoryExistsAsync(directory, this.RequestOptions, this.OperationContext, this.CmdletCancellationToken);
            }
            catch (StorageException e)
            {
                if (e.RequestInformation != null &&
                    e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.BadRequest &&
                    e.RequestInformation.ExtendedErrorInformation == null)
                {
                    throw new AzureStorageFileException(ErrorCategory.InvalidArgument, ErrorIdConstants.InvalidResource, Resources.InvalidResource, this);
                }

                throw;
            }

            if (directoryExists)
            {
                // If the directory exist on the cloud, we treat the path as
                // to a directory. So we append the default file name after
                // it and build an instance of CloudFile class.
                return(directory.GetFileReference(defaultFileName));
            }
            else
            {
                // If the directory does not exist, we treat the path as to a
                // file. So we use the path of the directory to build out a
                // new instance of CloudFile class.
                return(baseDirectory.GetFileReferenceByPath(path));
            }
        }
        public override void ExecuteCmdlet()
        {
            if (this.ShouldProcess(string.Format("Close File Handles for File or FileDirectory on Path: {0}", this.Path != null? this.Path : (this.FileHandle != null? this.FileHandle.Path: null)), "This operation will force the provided file handle(s) closed, which may cause data loss or corruption for active applications/users.", null))
            {
                CloudFileDirectory baseDirectory = null;
                switch (this.ParameterSetName)
                {
                case DirectoryCloseAllParameterSetName:
                    baseDirectory = this.Directory;
                    break;

                case ShareNameCloseSingleParameterSetName:
                case ShareNameCloseAllParameterSetName:
                    baseDirectory = this.BuildFileShareObjectFromName(this.ShareName).GetRootDirectoryReference();
                    break;

                case ShareCloseSingleParameterSetName:
                case ShareCloseAllParameterSetName:
                    baseDirectory = this.Share.GetRootDirectoryReference();
                    break;

                case FileCloseAllParameterSetName:
                    // Don't need to set baseDirectory when input is a CloudFile
                    break;

                default:
                    throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName));
                }

                if (ParameterSetName == ShareNameCloseSingleParameterSetName || ParameterSetName == ShareCloseSingleParameterSetName)
                {
                    this.Path = FileHandle.Path;
                }

                // When not input path/File, the list handle target must be a Dir
                bool foundAFolder             = true;
                CloudFileDirectory targetDir  = baseDirectory;
                CloudFile          targetFile = null;
                if (this.File != null)
                {
                    targetFile   = this.File;
                    foundAFolder = false;
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.Path))
                    {
                        string[] subfolders = NamingUtil.ValidatePath(this.Path);
                        targetDir = baseDirectory.GetDirectoryReferenceByPath(subfolders);

                        // Don't need check the path target to File or FileDir since:
                        // 1. check File/FileDir exist will fail on File/FileDir with DeletePending status
                        // 2. The File handle request send with CloudFileDirectory and CloudFile are same with same path, so need to differ it.
                    }
                }

                // Recursive only take effect on File Dir
                if (!foundAFolder && Recursive.IsPresent)
                {
                    WriteVerbose("The target object of the 'Path' is an Azure File, the parameter '-Recursive' won't take effect.");
                }

                //Close handle
                CloseFileHandleResultSegment closeResult       = null;
                FileContinuationToken        continuationToken = null;
                int numHandlesClosed = 0;
                do
                {
                    if (foundAFolder)
                    {
                        if (FileHandle != null)
                        {
                            // close single handle on fileDir
                            if (this.FileHandle.HandleId == null)
                            {
                                throw new System.ArgumentException(string.Format("The HandleId of the FileHandle on path {0} should not be null.", this.FileHandle.Path), "FileHandle");
                            }
                            closeResult = targetDir.CloseHandleSegmented(this.FileHandle.HandleId.ToString(), continuationToken, Recursive, null, this.RequestOptions, this.OperationContext);
                        }
                        else
                        {
                            // close all handle on fileDir
                            closeResult = targetDir.CloseAllHandlesSegmented(continuationToken, Recursive, null, this.RequestOptions, this.OperationContext);
                        }
                    }
                    else
                    {
                        if (FileHandle != null)
                        {
                            // close single handle on file
                            if (this.FileHandle.HandleId == null)
                            {
                                throw new System.ArgumentException(string.Format("The HandleId of the FileHandle on path {0} should not be null.", this.FileHandle.Path), "FileHandle");
                            }
                            closeResult = targetFile.CloseHandleSegmented(this.FileHandle.HandleId.ToString(), continuationToken, null, this.RequestOptions, this.OperationContext);
                        }
                        else
                        {
                            // close all handle on file
                            closeResult = targetFile.CloseAllHandlesSegmented(continuationToken, null, this.RequestOptions, this.OperationContext);
                        }
                    }
                    numHandlesClosed += closeResult.NumHandlesClosed;
                    continuationToken = closeResult.ContinuationToken;
                } while (continuationToken != null && continuationToken.NextMarker != null);

                if (PassThru)
                {
                    WriteObject(numHandlesClosed);
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            CloudFileDirectory baseDirectory = null;

            switch (this.ParameterSetName)
            {
            case Constants.DirectoryParameterSetName:
                baseDirectory = this.Directory;
                break;

            case Constants.ShareNameParameterSetName:
                baseDirectory = this.BuildFileShareObjectFromName(this.ShareName).GetRootDirectoryReference();
                break;

            case Constants.ShareParameterSetName:
                baseDirectory = this.Share.GetRootDirectoryReference();
                break;

            case Constants.FileParameterSetName:
                // Don't need to set baseDirectory when input is a CloudFile
                break;

            default:
                throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName));
            }

            // When not input path/File, the list handle target must be a Dir
            bool foundAFolder             = true;
            CloudFileDirectory targetDir  = baseDirectory;
            CloudFile          targetFile = null;

            if (this.File != null)
            {
                targetFile   = this.File;
                foundAFolder = false;
            }
            else
            {
                if (!string.IsNullOrEmpty(this.Path))
                {
                    string[] subfolders = NamingUtil.ValidatePath(this.Path);
                    targetDir = baseDirectory.GetDirectoryReferenceByPath(subfolders);

                    if (!targetDir.Exists())
                    {
                        foundAFolder = false;
                    }

                    if (!foundAFolder)
                    {
                        //Get file
                        string[] filePath = NamingUtil.ValidatePath(this.Path, true);
                        targetFile = baseDirectory.GetFileReferenceByPath(filePath);

                        this.Channel.FetchFileAttributesAsync(
                            targetFile,
                            null,
                            this.RequestOptions,
                            this.OperationContext,
                            this.CmdletCancellationToken).ConfigureAwait(false);
                    }
                }
            }

            // Recursive only take effect on File Dir
            if (!foundAFolder && Recursive.IsPresent)
            {
                WriteVerbose("The target object of the 'Path' is an Azure File, the parameter '-Recursive' won't take effect.");
            }

            //List handle
            FileHandleResultSegment listResult;
            FileContinuationToken   continuationToken = null;
            List <PSFileHandle>     handleReturn      = new List <PSFileHandle>();
            ulong first = MyInvocation.BoundParameters.ContainsKey("First") ? this.PagingParameters.First : ulong.MaxValue;
            ulong skip  = MyInvocation.BoundParameters.ContainsKey("Skip") ? this.PagingParameters.Skip : 0;

            // Any items before this count should be return
            ulong lastCount    = MyInvocation.BoundParameters.ContainsKey("First") ? skip + first : ulong.MaxValue;
            ulong currentCount = 0;

            do
            {
                if (foundAFolder)
                {
                    // list handle on fileDir
                    listResult = targetDir.ListHandlesSegmented(continuationToken, null, Recursive, null, this.RequestOptions, this.OperationContext);
                }
                else
                {
                    // list handle on file
                    listResult = targetFile.ListHandlesSegmented(continuationToken, null, null, this.RequestOptions, this.OperationContext);
                }

                List <FileHandle> handleList = new List <FileHandle>(listResult.Results);

                if (currentCount + (ulong)handleList.Count - 1 < skip)
                {
                    // skip the whole chunk if they are all in skip
                    currentCount += (ulong)handleList.Count;
                }
                else
                {
                    foreach (FileHandle handle in handleList)
                    {
                        // not return "skip" count of items in the begin, and only return "first" count of items after that.
                        if (currentCount >= skip && currentCount < lastCount)
                        {
                            handleReturn.Add(new PSFileHandle(handle));
                        }
                        currentCount++;
                        if (currentCount >= lastCount)
                        {
                            break;
                        }
                    }
                }
                continuationToken = listResult.ContinuationToken;
            } while (continuationToken != null && continuationToken.NextMarker != null && currentCount < lastCount);

            WriteObject(handleReturn, true);
        }