本文整理汇总了C#中Microsoft.WindowsAzure.Storage.Blob.CloudBlob类的典型用法代码示例。如果您正苦于以下问题:C# CloudBlob类的具体用法?C# CloudBlob怎么用?C# CloudBlob使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CloudBlob类属于Microsoft.WindowsAzure.Storage.Blob命名空间,在下文中一共展示了CloudBlob类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: TestAccess
private static void TestAccess(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, CloudBlob blob)
{
CloudBlob SASblob;
StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
new StorageCredentials() :
new StorageCredentials(sasToken);
if (container != null)
{
container = new CloudBlobContainer(credentials.TransformUri(container.Uri));
if (blob.BlobType == BlobType.BlockBlob)
{
SASblob = container.GetBlockBlobReference(blob.Name);
}
else if (blob.BlobType == BlobType.PageBlob)
{
SASblob = container.GetPageBlobReference(blob.Name);
}
else
{
SASblob = container.GetAppendBlobReference(blob.Name);
}
}
else
{
if (blob.BlobType == BlobType.BlockBlob)
{
SASblob = new CloudBlockBlob(credentials.TransformUri(blob.Uri));
}
else if (blob.BlobType == BlobType.PageBlob)
{
SASblob = new CloudPageBlob(credentials.TransformUri(blob.Uri));
}
else
{
SASblob = new CloudAppendBlob(credentials.TransformUri(blob.Uri));
}
}
HttpStatusCode failureCode = sasToken == null ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden;
// We want to ensure that 'create', 'add', and 'write' permissions all allow for correct writing of blobs, as is reasonable.
if (((permissions & SharedAccessBlobPermissions.Create) == SharedAccessBlobPermissions.Create) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
{
if (blob.BlobType == BlobType.PageBlob)
{
CloudPageBlob SASpageBlob = (CloudPageBlob)SASblob;
SASpageBlob.Create(512);
CloudPageBlob pageBlob = (CloudPageBlob)blob;
byte[] buffer = new byte[512];
buffer[0] = 2; // random data
if (((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
{
SASpageBlob.UploadFromByteArray(buffer, 0, 512);
}
else
{
TestHelper.ExpectedException(
() => SASpageBlob.UploadFromByteArray(buffer, 0, 512),
"pageBlob SAS token without Write perms should not allow for writing/adding",
failureCode);
pageBlob.UploadFromByteArray(buffer, 0, 512);
}
}
else if (blob.BlobType == BlobType.BlockBlob)
{
if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
{
UploadText(SASblob, "blob", Encoding.UTF8);
}
else
{
TestHelper.ExpectedException(
() => UploadText(SASblob, "blob", Encoding.UTF8),
"Block blob SAS token without Write or perms should not allow for writing",
failureCode);
UploadText(blob, "blob", Encoding.UTF8);
}
}
else // append blob
{
// If the sas token contains Feb 2012, append won't be accepted
if (sasToken.Contains(Constants.VersionConstants.February2012))
{
UploadText(blob, "blob", Encoding.UTF8);
}
else
{
CloudAppendBlob SASAppendBlob = SASblob as CloudAppendBlob;
SASAppendBlob.CreateOrReplace();
byte[] textAsBytes = Encoding.UTF8.GetBytes("blob");
using (MemoryStream stream = new MemoryStream())
{
stream.Write(textAsBytes, 0, textAsBytes.Length);
stream.Seek(0, SeekOrigin.Begin);
if (((permissions & SharedAccessBlobPermissions.Add) == SharedAccessBlobPermissions.Add) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
{
//.........这里部分代码省略.........
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:101,代码来源:SASTests.cs
示例2: AzureBlobLocation
/// <summary>
/// Initializes a new instance of the <see cref="AzureBlobLocation"/> class.
/// </summary>
/// <param name="blob">CloudBlob instance as a location in a transfer job.
/// It could be a source, a destination.</param>
public AzureBlobLocation(CloudBlob blob)
{
if (null == blob)
{
throw new ArgumentNullException("blob");
}
this.Blob = blob;
}
开发者ID:ggais,项目名称:azure-storage-net-data-movement,代码行数:14,代码来源:AzureBlobLocation.cs
示例3: PutNextEntry
protected override void PutNextEntry(CloudBlob blob)
{
var entry = TarEntry.CreateTarEntry(GetEntryName(blob));
entry.Size = blob.Properties.Length;
entry.ModTime = (blob.Properties.LastModified ?? new DateTimeOffset(2000, 01, 01, 00, 00, 00, TimeSpan.Zero)).UtcDateTime;
_archiveStream.PutNextEntry(entry);
}
开发者ID:glueckkanja,项目名称:azure-blob-to-archive,代码行数:9,代码来源:TarCore.cs
示例4: WaitForCopyAsync
public static async Task WaitForCopyAsync(CloudBlob blob)
{
bool copyInProgress = true;
while (copyInProgress)
{
await Task.Delay(1000);
await blob.FetchAttributesAsync();
copyInProgress = (blob.CopyState.Status == CopyStatus.Pending);
}
}
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:10,代码来源:BlobTestBase.cs
示例5: AzureStorageBlob
/// <summary>
/// Azure storage blob constructor
/// </summary>
/// <param name="blob">ICloud blob object</param>
public AzureStorageBlob(CloudBlob blob)
{
Name = blob.Name;
ICloudBlob = blob;
BlobType = blob.BlobType;
Length = blob.Properties.Length;
ContentType = blob.Properties.ContentType;
LastModified = blob.Properties.LastModified;
SnapshotTime = blob.SnapshotTime;
}
开发者ID:docschmidt,项目名称:azure-powershell,代码行数:14,代码来源:AzureStorageBlob.cs
示例6: WaitForCopyTask
public static void WaitForCopyTask(CloudBlob blob)
{
bool copyInProgress = true;
while (copyInProgress)
{
Thread.Sleep(1000);
blob.FetchAttributesAsync().Wait();
copyInProgress = (blob.CopyState.Status == CopyStatus.Pending);
}
}
开发者ID:Gajendra-Bahakar,项目名称:azure-storage-net,代码行数:10,代码来源:BlobTestBase.cs
示例7: LoadBlobBytesAsync
public async Task<byte[]> LoadBlobBytesAsync(Uri location)
{
var blob = new CloudBlob (location);
await blob.FetchAttributesAsync ();
byte[] target = new byte[blob.Properties.Length];
await blob.DownloadToByteArrayAsync (target, 0);
return target;
}
开发者ID:codemillmatt,项目名称:CheesedStorage,代码行数:12,代码来源:CheeseStorageService.cs
示例8: TestAccessTask
private static void TestAccessTask(BlobContainerPublicAccessType accessType, CloudBlobContainer container, CloudBlob inputBlob)
{
StorageCredentials credentials = new StorageCredentials();
container = new CloudBlobContainer(container.Uri, credentials);
CloudPageBlob blob = new CloudPageBlob(inputBlob.Uri, credentials);
if (accessType.Equals(BlobContainerPublicAccessType.Container))
{
blob.FetchAttributesAsync().Wait();
BlobContinuationToken token = null;
do
{
BlobResultSegment results = container.ListBlobsSegmented(token);
results.Results.ToArray();
token = results.ContinuationToken;
}
while (token != null);
container.FetchAttributesAsync().Wait();
}
else if (accessType.Equals(BlobContainerPublicAccessType.Blob))
{
blob.FetchAttributesAsync().Wait();
TestHelper.ExpectedExceptionTask(
container.ListBlobsSegmentedAsync(null),
"List blobs while public access does not allow for listing",
HttpStatusCode.NotFound);
TestHelper.ExpectedExceptionTask(
container.FetchAttributesAsync(),
"Fetch container attributes while public access does not allow",
HttpStatusCode.NotFound);
}
else
{
TestHelper.ExpectedExceptionTask(
blob.FetchAttributesAsync(),
"Fetch blob attributes while public access does not allow",
HttpStatusCode.NotFound);
TestHelper.ExpectedExceptionTask(
container.ListBlobsSegmentedAsync(null),
"List blobs while public access does not allow for listing",
HttpStatusCode.NotFound);
TestHelper.ExpectedExceptionTask(
container.FetchAttributesAsync(),
"Fetch container attributes while public access does not allow",
HttpStatusCode.NotFound);
}
}
开发者ID:Gajendra-Bahakar,项目名称:azure-storage-net,代码行数:48,代码来源:CloudBlobContainerTest.cs
示例9: TestAccessAsync
private static async Task TestAccessAsync(BlobContainerPublicAccessType accessType, CloudBlobContainer container, CloudBlob inputBlob)
{
StorageCredentials credentials = new StorageCredentials();
container = new CloudBlobContainer(container.Uri, credentials);
CloudPageBlob blob = new CloudPageBlob(inputBlob.Uri, credentials);
OperationContext context = new OperationContext();
BlobRequestOptions options = new BlobRequestOptions();
if (accessType.Equals(BlobContainerPublicAccessType.Container))
{
await blob.FetchAttributesAsync();
await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context);
await container.FetchAttributesAsync();
}
else if (accessType.Equals(BlobContainerPublicAccessType.Blob))
{
await blob.FetchAttributesAsync();
await TestHelper.ExpectedExceptionAsync(
async () => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context),
context,
"List blobs while public access does not allow for listing",
HttpStatusCode.NotFound);
await TestHelper.ExpectedExceptionAsync(
async () => await container.FetchAttributesAsync(null, options, context),
context,
"Fetch container attributes while public access does not allow",
HttpStatusCode.NotFound);
}
else
{
await TestHelper.ExpectedExceptionAsync(
async () => await blob.FetchAttributesAsync(null, options, context),
context,
"Fetch blob attributes while public access does not allow",
HttpStatusCode.NotFound);
await TestHelper.ExpectedExceptionAsync(
async () => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context),
context,
"List blobs while public access does not allow for listing",
HttpStatusCode.NotFound);
await TestHelper.ExpectedExceptionAsync(
async () => await container.FetchAttributesAsync(null, options, context),
context,
"Fetch container attributes while public access does not allow",
HttpStatusCode.NotFound);
}
}
开发者ID:mirobers,项目名称:azure-storage-net,代码行数:48,代码来源:CloudBlobContainerTest.cs
示例10: Equals
/// <summary>
/// Determines whether two blobs have the same Uri and SnapshotTime.
/// </summary>
/// <param name="blob">Blob to compare.</param>
/// <param name="comparand">Comparand object.</param>
/// <returns>True if the two blobs have the same Uri and SnapshotTime; otherwise, false.</returns>
internal static bool Equals(
CloudBlob blob,
CloudBlob comparand)
{
if (blob == comparand)
{
return true;
}
if (null == blob || null == comparand)
{
return false;
}
return blob.Uri.Equals(comparand.Uri) &&
blob.SnapshotTime.Equals(comparand.SnapshotTime);
}
开发者ID:ggais,项目名称:azure-storage-net-data-movement,代码行数:23,代码来源:StorageExtensions.cs
示例11: CreateVideo
private Video CreateVideo(CloudBlob blob)
{
if (blob == null)
{
return null;
}
blob.FetchAttributes();
return new Video
{
Title = blob.Metadata[NameField],
Name = blob.Name,
StorageUrl = blob.Uri.ToString(),
ContentDeliveryNetworkUrl = $"https://{_config.CdnEndpointName}.vo.msecnd.net/{ContainerName}/{blob.Name}"
};
}
开发者ID:kpi-ua,项目名称:MediaHack,代码行数:17,代码来源:Cloud.cs
示例12: BlobReadStreamBase
/// <summary>
/// Initializes a new instance of the BlobReadStreamBase class.
/// </summary>
/// <param name="blob">Blob reference to read from</param>
/// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the condition that must be met in order for the request to proceed. If <c>null</c>, no condition is used.</param>
/// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies additional options for the request.</param>
/// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
protected BlobReadStreamBase(CloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
if (options.UseTransactionalMD5.Value)
{
CommonUtility.AssertInBounds("StreamMinimumReadSizeInBytes", blob.StreamMinimumReadSizeInBytes, 1, Constants.MaxRangeGetContentMD5Size);
}
this.blob = blob;
this.blobProperties = new BlobProperties(blob.Properties);
this.currentOffset = 0;
this.streamMinimumReadSizeInBytes = this.blob.StreamMinimumReadSizeInBytes;
this.internalBuffer = new MultiBufferMemoryStream(blob.ServiceClient.BufferManager);
this.accessCondition = accessCondition;
this.options = options;
this.operationContext = operationContext;
this.blobMD5 = (this.options.DisableContentMD5Validation.Value || string.IsNullOrEmpty(this.blobProperties.ContentMD5)) ? null : new MD5Wrapper();
this.lastException = null;
}
开发者ID:Gajendra-Bahakar,项目名称:azure-storage-net,代码行数:25,代码来源:BlobReadStreamBase.cs
示例13: AssertAreEqual
public static void AssertAreEqual(CloudBlob expected, CloudBlob actual)
{
if (expected == null)
{
Assert.IsNull(actual);
}
else
{
Assert.IsNotNull(actual);
Assert.AreEqual(expected.BlobType, actual.BlobType);
Assert.AreEqual(expected.Uri, actual.Uri);
Assert.AreEqual(expected.StorageUri, actual.StorageUri);
Assert.AreEqual(expected.SnapshotTime, actual.SnapshotTime);
Assert.AreEqual(expected.IsSnapshot, actual.IsSnapshot);
Assert.AreEqual(expected.SnapshotQualifiedUri, actual.SnapshotQualifiedUri);
AssertAreEqual(expected.Properties, actual.Properties);
AssertAreEqual(expected.CopyState, actual.CopyState);
}
}
开发者ID:Gajendra-Bahakar,项目名称:azure-storage-net,代码行数:19,代码来源:BlobTestBase.Common.cs
示例14: TestAccess
private static void TestAccess(BlobContainerPublicAccessType accessType, CloudBlobContainer container, CloudBlob inputBlob)
{
StorageCredentials credentials = new StorageCredentials();
container = new CloudBlobContainer(container.Uri, credentials);
CloudPageBlob blob = new CloudPageBlob(inputBlob.Uri, credentials);
if (accessType.Equals(BlobContainerPublicAccessType.Container))
{
blob.FetchAttributes();
container.ListBlobs().ToArray();
container.FetchAttributes();
}
else if (accessType.Equals(BlobContainerPublicAccessType.Blob))
{
blob.FetchAttributes();
TestHelper.ExpectedException(
() => container.ListBlobs().ToArray(),
"List blobs while public access does not allow for listing",
HttpStatusCode.NotFound);
TestHelper.ExpectedException(
() => container.FetchAttributes(),
"Fetch container attributes while public access does not allow",
HttpStatusCode.NotFound);
}
else
{
TestHelper.ExpectedException(
() => blob.FetchAttributes(),
"Fetch blob attributes while public access does not allow",
HttpStatusCode.NotFound);
TestHelper.ExpectedException(
() => container.ListBlobs().ToArray(),
"List blobs while public access does not allow for listing",
HttpStatusCode.NotFound);
TestHelper.ExpectedException(
() => container.FetchAttributes(),
"Fetch container attributes while public access does not allow",
HttpStatusCode.NotFound);
}
}
开发者ID:Gajendra-Bahakar,项目名称:azure-storage-net,代码行数:40,代码来源:CloudBlobContainerTest.cs
示例15: BlobAsyncCopyController
public BlobAsyncCopyController(
TransferScheduler transferScheduler,
TransferJob transferJob,
CancellationToken cancellationToken)
: base(transferScheduler, transferJob, cancellationToken)
{
this.destLocation = transferJob.Destination as AzureBlobLocation;
CloudBlob transferDestBlob = this.destLocation.Blob;
if (null == transferDestBlob)
{
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
Resources.ParameterCannotBeNullException,
"Dest.Blob"),
"transferJob");
}
if (transferDestBlob.IsSnapshot)
{
throw new ArgumentException(Resources.DestinationMustBeBaseBlob, "transferJob");
}
AzureBlobLocation sourceBlobLocation = transferJob.Source as AzureBlobLocation;
if (sourceBlobLocation != null)
{
if (sourceBlobLocation.Blob.BlobType != transferDestBlob.BlobType)
{
throw new ArgumentException(Resources.SourceAndDestinationBlobTypeDifferent, "transferJob");
}
if (StorageExtensions.Equals(sourceBlobLocation.Blob, transferDestBlob))
{
throw new InvalidOperationException(Resources.SourceAndDestinationLocationCannotBeEqualException);
}
}
this.destBlob = transferDestBlob;
}
开发者ID:ggais,项目名称:azure-storage-net-data-movement,代码行数:39,代码来源:BlobAsyncCopyController.cs
示例16: SavePageBlob
public void SavePageBlob(CloudBlobContainer container, CloudBlob blob)
{
var blobRef = _container.GetPageBlobReference(blob.Name);
var path = Path.Combine(ConfigurationManager.AppSettings["BlobSavePath"], blob.Name);
Console.WriteLine("Will save to: {0}", path);
using (var fileStream = File.OpenWrite(path))
{
var sw = new Stopwatch();
sw.Start();
var bla = blobRef.DownloadToStreamAsync(fileStream);
while (bla.IsCompleted == false)
{
Console.WriteLine("Status:{0}-{1}", bla.Status, DateTime.Now.ToShortTimeString());
Thread.Sleep(1000);
}
}
}
开发者ID:LFSb,项目名称:AzureBlobList,代码行数:23,代码来源:BlobDownloader.cs
示例17: GetBlobReferenceFromServer
private static CloudBlob GetBlobReferenceFromServer(
CloudBlob blob,
AccessCondition accessCondition = null,
BlobRequestOptions options = null,
OperationContext operationContext = null)
{
try
{
blob.FetchAttributes(accessCondition, options, operationContext);
}
catch (StorageException se)
{
if (se.RequestInformation == null ||
(se.RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound))
{
throw;
}
return null;
}
return GetCorrespondingTypeBlobReference(blob);
}
开发者ID:docschmidt,项目名称:azure-powershell,代码行数:23,代码来源:Util.cs
示例18: UploadTextAsync
public static async Task UploadTextAsync(CloudBlob blob, string text, Encoding encoding, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
{
byte[] textAsBytes = encoding.GetBytes(text);
using (MemoryStream stream = new MemoryStream())
{
await stream.WriteAsync(textAsBytes, 0, textAsBytes.Length);
if (blob.BlobType == BlobType.PageBlob)
{
int lastPageSize = (int)(stream.Length % 512);
if (lastPageSize != 0)
{
byte[] padding = new byte[512 - lastPageSize];
await stream.WriteAsync(padding, 0, padding.Length);
}
}
stream.Seek(0, SeekOrigin.Begin);
blob.ServiceClient.DefaultRequestOptions.ParallelOperationThreadCount = 2;
if (blob.BlobType == BlobType.AppendBlob)
{
CloudAppendBlob blob1 = blob as CloudAppendBlob;
await blob1.CreateOrReplaceAsync();
await blob1.AppendBlockAsync(stream, null);
}
else if (blob.BlobType == BlobType.PageBlob)
{
CloudPageBlob pageBlob = blob as CloudPageBlob;
await pageBlob.UploadFromStreamAsync(stream, accessCondition, options, operationContext);
}
else
{
CloudBlockBlob blockBlob = blob as CloudBlockBlob;
await blockBlob.UploadFromStreamAsync(stream, accessCondition, options, operationContext);
}
}
}
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:37,代码来源:BlobTestBase.cs
示例19: CloudBlobSASSharedProtocolsQueryParam
public void CloudBlobSASSharedProtocolsQueryParam()
{
CloudBlobContainer container = GetRandomContainerReference();
try
{
container.Create();
CloudBlob blob;
SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
};
CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
blockBlob.PutBlockList(new string[] { });
foreach (SharedAccessProtocol? protocol in new SharedAccessProtocol?[] { null, SharedAccessProtocol.HttpsOrHttp, SharedAccessProtocol.HttpsOnly })
{
string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, protocol, null);
StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken);
Uri blockBlobSASUri = new Uri(blockBlob.Uri + blockBlobSAS.SASToken);
StorageUri blockBlobSASStorageUri = new StorageUri(new Uri(blockBlob.StorageUri.PrimaryUri + blockBlobSAS.SASToken), new Uri(blockBlob.StorageUri.SecondaryUri + blockBlobSAS.SASToken));
int httpPort = blockBlobSASUri.Port;
int securePort = 443;
if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.BlobSecurePortOverride))
{
securePort = Int32.Parse(TestBase.TargetTenantConfig.BlobSecurePortOverride);
}
var schemesAndPorts = new[] {
new { scheme = Uri.UriSchemeHttp, port = httpPort},
new { scheme = Uri.UriSchemeHttps, port = securePort}
};
foreach (var item in schemesAndPorts)
{
blockBlobSASUri = TransformSchemeAndPort(blockBlobSASUri, item.scheme, item.port);
blockBlobSASStorageUri = new StorageUri(TransformSchemeAndPort(blockBlobSASStorageUri.PrimaryUri, item.scheme, item.port), TransformSchemeAndPort(blockBlobSASStorageUri.SecondaryUri, item.scheme, item.port));
if (protocol.HasValue && protocol.Value == SharedAccessProtocol.HttpsOnly && string.CompareOrdinal(item.scheme, Uri.UriSchemeHttp) == 0)
{
blob = new CloudBlob(blockBlobSASUri);
TestHelper.ExpectedException(() => blob.FetchAttributes(), "Access a blob using SAS with a shared protocols that does not match", HttpStatusCode.Unused);
blob = new CloudBlob(blockBlobSASStorageUri, null, null);
TestHelper.ExpectedException(() => blob.FetchAttributes(), "Access a blob using SAS with a shared protocols that does not match", HttpStatusCode.Unused);
}
else
{
blob = new CloudBlob(blockBlobSASUri);
blob.FetchAttributes();
Assert.AreEqual(blob.BlobType, BlobType.BlockBlob);
blob = new CloudBlob(blockBlobSASStorageUri, null, null);
blob.FetchAttributes();
Assert.AreEqual(blob.BlobType, BlobType.BlockBlob);
}
}
}
}
finally
{
container.DeleteIfExists();
}
}
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:68,代码来源:SASTests.cs
示例20: CloudBlobSASIPAddressHelper
/// <summary>
/// Helper function for testing the IPAddressOrRange funcitonality for blobs
/// </summary>
/// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param>
/// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object
/// that should be accepted by the service</param>
public void CloudBlobSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
{
CloudBlobContainer container = GetRandomContainerReference();
try
{
container.Create();
CloudBlob blob;
SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
};
CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 };
blockBlob.UploadFromByteArray(data, 0, 4);
// The plan then is to use an incorrect IP address to make a call to the service
// ensure that we get an error message
// parse the error message to get my actual IP (as far as the service sees)
// then finally test the success case to ensure we can actually make requests
IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange();
string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken);
Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri);
StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);
blob = new CloudBlob(blockBlobSASUri);
byte[] target = new byte[4];
OperationContext opContext = new OperationContext();
IPAddress actualIP = null;
opContext.ResponseReceived += (sender, e) =>
{
Stream stream = e.Response.GetResponseStream();
stream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(stream))
{
string text = reader.ReadToEnd();
XDocument xdocument = XDocument.Parse(text);
actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value);
}
};
bool exceptionThrown = false;
try
{
blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext);
}
catch (StorageException)
{
exceptionThrown = true;
Assert.IsNotNull(actualIP);
}
Assert.IsTrue(exceptionThrown);
ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
blockBlobSAS = new StorageCredentials(blockBlobToken);
blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri);
blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);
blob = new CloudBlob(blockBlobSASUri);
blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
for (int i = 0; i < 4; i++)
{
Assert.AreEqual(data[i], target[i]);
}
Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
Assert.IsNull(blob.StorageUri.SecondaryUri);
blob = new CloudBlob(blockBlobSASStorageUri, null, null);
blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
for (int i = 0; i < 4; i++)
{
Assert.AreEqual(data[i], target[i]);
}
Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));
}
finally
{
container.DeleteIfExists();
}
}
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:93,代码来源:SASTests.cs
注:本文中的Microsoft.WindowsAzure.Storage.Blob.CloudBlob类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论