示例#1
0
 public SensorAccess()
 {
     credentials = new StorageCredentials(_accountName, _key);
     storageAccount = new CloudStorageAccount(credentials, true);
     tableClient = storageAccount.CreateCloudTableClient();
     table = tableClient.GetTableReference("AccelerometerTable");
 }
        /// <summary>Initializes a new instance of the <see cref="CloudQueueClient"/> class.</summary>
        /// <param name="usePathStyleUris">True to use path style Uris. </param>
        /// <param name="baseAddressUri">The base address Uri. </param>
        /// <param name="credentials">The credentials. </param>
        internal CloudQueueClient(bool? usePathStyleUris, Uri baseAddressUri, StorageCredentials credentials)
        {
            CommonUtils.AssertNotNull("baseAddress", baseAddressUri);
            CommonUtils.AssertNotNull("credentials", credentials);

            if (!credentials.CanSignRequest)
            {
                throw new ArgumentException(SR.CredentialsCantSignRequest, "credentials");
            }

            this.BaseUri = baseAddressUri;

            if (!this.BaseUri.IsAbsoluteUri)
            {
                CommonUtils.ArgumentOutOfRange("baseAddress", baseAddressUri);
            }

            this.Timeout = Constants.DefaultClientSideTimeout;
            this.RetryPolicy = RetryPolicies.RetryExponential(
                RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultClientBackoff);
            this.Credentials = credentials;

            // if use path style uris doesn't have a value, automatically decide whether to use host style uri or path style uri
            this.UsePathStyleUris = usePathStyleUris.HasValue ? usePathStyleUris.Value : CommonUtils.UsePathStyleAddressing(this.BaseUri);
        }
        /// <summary>Initializes a new instance of the <see cref="TableServiceContext"/> class.</summary>
        /// <param name="baseAddress">The Table service endpoint to use create the service context. </param>
        /// <param name="credentials">The account credentials. </param>
        public TableServiceContext(string baseAddress, StorageCredentials credentials)
            : base(new Uri(baseAddress))
        {
            if (string.IsNullOrEmpty(baseAddress))
            {
                throw new ArgumentNullException("baseAddress");
            }

            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }

            if ((!credentials.CanSignRequest) || (!credentials.CanSignRequestLite))
            {
                throw new ArgumentException(SR.CredentialsCantSignRequest, "credentials");
            }

            this.SendingRequest += this.DataContextSendingRequest;

            this.StorageCredentials = credentials;
            this.IgnoreMissingProperties = true;
            this.MergeOption = MergeOption.PreserveChanges;

            this.RetryPolicy = RetryPolicies.RetryExponential(
                RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultClientBackoff);
            this.Timeout = (int)TimeSpan.FromSeconds(90).TotalSeconds;
        }
示例#4
0
        public virtual Uri UploadFile(
            string storageName,
            Uri blobEndpointUri,
            string storageKey,
            string filePath,
            BlobRequestOptions blobRequestOptions)
        {
            StorageCredentials credentials = new StorageCredentials(storageName, storageKey);
            CloudBlobClient client = new CloudBlobClient(blobEndpointUri, credentials);
            string blobName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}_{1}",
                DateTime.UtcNow.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture),
                Path.GetFileName(filePath));

            CloudBlobContainer container = client.GetContainerReference(ContainerName);
            container.CreateIfNotExists();
            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

            BlobRequestOptions uploadRequestOption = blobRequestOptions ?? new BlobRequestOptions();

            if (!uploadRequestOption.ServerTimeout.HasValue)
            {
                uploadRequestOption.ServerTimeout = TimeSpan.FromMinutes(300);
            }

            using (FileStream readStream = File.OpenRead(filePath))
            {
                blob.UploadFromStream(readStream, AccessCondition.GenerateEmptyCondition(), uploadRequestOption);
            }

            return new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", client.BaseUri, ContainerName, client.DefaultDelimiter, blobName));
        }
 public TableStorageAppender(StorageCredentials credentials)
 {
     if (credentials.AccountName.StartsWith("devstoreaccount"))
         StorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
     else
         StorageAccount = new CloudStorageAccount(credentials, true);
     TableName = "WADLogsTable";
     TransferIntervalInMinutes = 5;
     LogmarkerIntervalInMinutes = 30;
 }
 public static void DeletePackageFromBlob(IServiceManagement channel, string storageName, string subscriptionId, Uri packageUri)
 {
     var storageService = channel.GetStorageKeys(subscriptionId, storageName);
     var storageKey = storageService.StorageServiceKeys.Primary;
     storageService = channel.GetStorageService(subscriptionId, storageName);
     var blobStorageEndpoint = new Uri(storageService.StorageServiceProperties.Endpoints.Find(p => p.Contains(BlobEndpointIdentifier)));
     var credentials = new StorageCredentials(storageName, storageKey);
     var client = new CloudBlobClient(blobStorageEndpoint, credentials);
     ICloudBlob blob = client.GetBlobReferenceFromServer(packageUri);
     blob.DeleteIfExists();
 }
示例#7
0
 public virtual void DeletePackageFromBlob(
     StorageManagementClient storageClient,
     string storageName,
     Uri packageUri)
 {
     StorageAccountGetKeysResponse keys = storageClient.StorageAccounts.GetKeys(storageName);
     string storageKey = keys.PrimaryKey;
     var storageService = storageClient.StorageAccounts.Get(storageName);
     var blobStorageEndpoint = storageService.StorageAccount.Properties.Endpoints[0];
     var credentials = new StorageCredentials(storageName, storageKey);
     var client = new CloudBlobClient(blobStorageEndpoint, credentials);
     ICloudBlob blob = client.GetBlobReferenceFromServer(packageUri);
     blob.DeleteIfExists();
 }
示例#8
0
        public static void RemoveVHD(IServiceManagement channel, string subscriptionId, Uri mediaLink)
        {
            var accountName = mediaLink.Host.Split('.')[0];
            var blobEndpoint = new Uri(mediaLink.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped));

            StorageService storageService;
            using (new OperationContextScope(channel.ToContextChannel()))
            {
                storageService = channel.GetStorageKeys(subscriptionId, accountName);
            }

            var storageAccountCredentials = new StorageCredentials(accountName, storageService.StorageServiceKeys.Primary);
            var client = new CloudBlobClient(blobEndpoint, storageAccountCredentials);
            var blob = client.GetBlobReferenceFromServer(mediaLink);
            blob.DeleteIfExists();
        }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudQueue"/> class.
        /// </summary>
        /// <param name="usePathStyleUris">True to use path style Uris.</param>
        /// <param name="address">The address.</param>
        /// <param name="credentials">The credentials.</param>
        internal CloudQueue(bool? usePathStyleUris, string address, StorageCredentials credentials)
        {
            CommonUtils.AssertNotNullOrEmpty("address", address);
            CommonUtils.AssertNotNull("credentials", credentials);

            if (!credentials.CanSignRequest)
            {
                throw new ArgumentException(SR.CredentialsCantSignRequest, "credentials");
            }

            this.EncodeMessage = true;
            this.attributes = new QueueAttributes() { Uri = new Uri(address) };

            string baseAddress = NavigationHelper.GetServiceClientBaseAddress(this.Uri, usePathStyleUris);

            this.ServiceClient = new CloudQueueClient(baseAddress, credentials);
            this.Name = NavigationHelper.GetQueueNameFromUri(this.Uri, this.ServiceClient.UsePathStyleUris);
        }
        /// <summary>
        /// Attempts to get the user's credentials from the given Storage Context or the current subscription, if the former is null. 
        /// Throws a terminating error if the credentials cannot be determined.
        /// </summary>
        public static StorageCredentials GetStorageCredentials(this ServiceManagementBaseCmdlet cmdlet, AzureStorageContext storageContext)
        {
            StorageCredentials credentials = null;

            if (storageContext != null)
            {
                credentials = storageContext.StorageAccount.Credentials;
            }
            else
            {
                var storageAccountName = cmdlet.CurrentSubscription.CurrentStorageAccountName;
                
                if (!string.IsNullOrEmpty(storageAccountName))
                {
                    var keys = cmdlet.StorageClient.StorageAccounts.GetKeys(storageAccountName);
                    
                    if (keys != null)
                    {
                        var storageAccountKey = string.IsNullOrEmpty(keys.PrimaryKey) ? keys.SecondaryKey : keys.PrimaryKey;

                        credentials = new StorageCredentials(storageAccountName, storageAccountKey);
                    }
                }
            }

            if (credentials == null)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new UnauthorizedAccessException(Resources.AzureVMDscDefaultStorageCredentialsNotFound),
                        string.Empty,
                        ErrorCategory.PermissionDenied,
                        null));
            }

            if (string.IsNullOrEmpty(credentials.AccountName))
            {
                cmdlet.ThrowInvalidArgumentError(Resources.AzureVMDscStorageContextMustIncludeAccountName);
            }

            return credentials;
        }
示例#11
0
        public Storage()
        {
            var accountName = WebConfigurationManager.AppSettings["AccountName"];
            var accountKey = WebConfigurationManager.AppSettings["AccountKey"];
            bool useHttps = WebConfigurationManager.AppSettings["DefaultEndpointsProtocol"].ToLower() == "https";

            StorageCredentials credentials = new StorageCredentials(accountName, accountKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, useHttps);

            // Create the blob client.
            var blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            Messages = blobClient.GetContainerReference("messages");
            Users = blobClient.GetContainerReference("users");

            // Create the container if it doesn't already exist.
            Messages.CreateIfNotExists();

            Users.CreateIfNotExists();
        }
示例#12
0
        internal List<ProductEntity> RetrieveTable()
        {
            StorageCredentials creds = new StorageCredentials(accountName, accountKey);
            CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
            CloudTableClient tableClient = account.CreateCloudTableClient();

            // Retrieve storage account from the connection string
               // CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
             //   ConfigurationManager.ConnectionStrings["BlobStorageConnectionString"].ConnectionString);

            // Create the table client
            //CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "product" table
            CloudTable table = tableClient.GetTableReference("products");

            // Construct the query operation for all product entities
            TableQuery<ProductEntity> query = new TableQuery<ProductEntity>();

            var products = table.ExecuteQuery(query).ToList();

            return products;
        }
示例#13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudQueue"/> class.
 /// </summary>
 /// <param name="address">The relative address.</param>
 /// <param name="credentials">The storage account credentials.</param>
 /// <param name="usePathStyleUris">If set to <c>true</c>, use path style Uris.</param>
 internal CloudQueue(string address, StorageCredentials credentials, bool usePathStyleUris)
     : this(usePathStyleUris, address, credentials)
 {
 }
        protected void InitializeStorageContext(string storageAccountName)
        {
            // lookup storage account by name and retrieve key 
            var storageService = this.StorageClient.StorageAccounts.Get(storageAccountName);
            if (storageService == null)
            {
                ThrowTerminatingError(new ErrorRecord(
                    new Exception("ServiceExtensionCannotFindStorageAccountName"),
                    string.Empty,
                    ErrorCategory.InvalidData,
                    null));
            }
            var storageKeys = this.StorageClient.StorageAccounts.GetKeys(storageService.StorageAccount.Name);
            if (storageKeys == null || storageKeys.PrimaryKey == null || storageKeys.SecondaryKey == null)
            {
                ThrowTerminatingError(new ErrorRecord(
                    new Exception("ServiceExtensionCannotFindStorageAccountKey"),
                    string.Empty,
                    ErrorCategory.InvalidData,
                    null));
            }
            string storageAccountKey = storageKeys.PrimaryKey != null ? storageKeys.PrimaryKey : storageKeys.SecondaryKey;

            // now that key has been retrieved, initialize context and return
            StorageCredentials creds = new StorageCredentials(storageAccountName, storageAccountKey);
            CloudStorageAccount csa = new WindowsAzure.Storage.CloudStorageAccount(creds, true);
            StorageContext = new AzureStorageContext(csa);
        }
        protected string GetSasUrlStr(string storageName, string storageKey, string containerName, string blobName)
        {
            var cred = new StorageCredentials(storageName, storageKey);
            var storageAccount = string.IsNullOrEmpty(this.StorageEndpointSuffix)
                               ? new CloudStorageAccount(cred, true)
                               : new CloudStorageAccount(cred, this.StorageEndpointSuffix, true);

            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(containerName);
            var cloudBlob = container.GetBlockBlobReference(blobName);
            var sasToken = cloudBlob.GetSharedAccessSignature(
                new SharedAccessBlobPolicy()
                {
                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24.0),
                    Permissions = SharedAccessBlobPermissions.Read
                });

            // Try not to use a Uri object in order to keep the following 
            // special characters in the SAS signature section:
            //     '+'   ->   '%2B'
            //     '/'   ->   '%2F'
            //     '='   ->   '%3D'
            return cloudBlob.Uri + sasToken;
        }
 public SharedKeyLiteAuthenticationHandler(ICanonicalizer canonicalizer, StorageCredentials credentials, string resourceAccountName)
 {
     this.canonicalizer = canonicalizer;
     this.credentials = credentials;
     this.resourceAccountName = resourceAccountName;
 }
示例#17
0
        private static void GenerateBulkInsertCommandList(Configuration config, string sasToken, string accountName, string container, string directory, string pattern)
        {
            string credentialName = null;

            if (StorageDataSource == null)
            {
                ValidateAzureStorageAccountParameters(ref sasToken, ref accountName, container);
                credentialName = "BULK-LOAD-" + accountName + "-" + DateTime.Now.ToShortDateString();
                ConfigureTempDataSource(config, sasToken, accountName, credentialName);
            }
            else
            {
                credentialName = StorageDataSource;
            }

            string[] list = null;
            if (!string.IsNullOrEmpty(sasToken))
            {
                pattern = pattern.Replace(".", "\\.").Replace("*", "\\w+");

                var sc = new StorageCredentials(sasToken);
                CloudStorageAccount storageAccount = new CloudStorageAccount(sc, accountName, "core.windows.net", true);

                var blobClient   = storageAccount.CreateCloudBlobClient();
                var srcContainer = blobClient.GetContainerReference(container);

                list = srcContainer
                       .ListBlobs(useFlatBlobListing: true, prefix: directory, blobListingDetails: BlobListingDetails.None)
                       .Where(blob => (blob is CloudBlockBlob) && Regex.IsMatch((blob as CloudBlockBlob).Name, pattern))
                       .Select(b => b.StorageUri.PrimaryUri.PathAndQuery.Trim("/".ToCharArray())).ToArray();
            }
            else
            {
                if (string.IsNullOrWhiteSpace(StorageDataSource))
                {
                    Exit("You need to specify either a Azure Blob Storage connection using -ACCOUNT, -SAS, and -CONTAINER command-line parameters or EXTERNAL DATA SOURCE name as -DATASOURCE command-line option.");
                }
                if (pattern.Contains('*'))
                {
                    Exit("SAS token is not provided so you cannot specify pattern for input files. Please remove * from input file specification, and put a list of files with comma(,).");
                }
                list = pattern.Split(',');
            }

            if (list.Length < config.WorkerThreads)
            {
                Console.WriteLine("Number of worker threads decreased from {0} to {1}", config.WorkerThreads, list.Length);
                config.WorkerThreads = (short)list.Length;
            }

            Console.WriteLine("Loading {0} files from {1} into {2} database on server {3}.\nPress [Y] to continue:", list.Length, !string.IsNullOrEmpty(sasToken) ? ("Storage account:" + accountName) : ("Storage datasource " + StorageDataSource), Database, Server);
            var confirmation = Console.ReadLine();

            if (confirmation.ToUpper() == "Y")
            {
                GenerateBulkInsertCommand(config, list, credentialName);
            }
            else
            {
                Exit("Cancelling operation.");
            }
        }
示例#18
0
        public AzurePath(string azureInfoPath, string path)
        {
            if (!path.StartsWith(AZURE_PATH_PREFIX))
            {
                throw new ArgumentException($"Azure paths need to be in the format {AZURE_PATH_PREFIX}/account_name/container_name/path, but got {path}.");
            }

            // Strip off azure:// prefix:
            var accountPath = path.Substring(AZURE_PATH_PREFIX.Length);
            var pathParts   = accountPath.Split(new char[] { '/' }, 3);

            if (pathParts.Length < 3)
            {
                throw new ArgumentException($"Azure paths need to be in the format {AZURE_PATH_PREFIX}/account_name/container_name/path, but got {path}.");
            }
            var(accountName, containerName, containerPath) = (pathParts[0], pathParts[1], pathParts[2]);

            using (var azureInfoInstream = File.OpenText(azureInfoPath))
                using (var azureInfoJsonReader = new JsonTextReader(azureInfoInstream))
                {
                    var deserializer = new JsonSerializer();
                    var azureInfo    = deserializer.Deserialize <Dictionary <string, Dictionary <string, string> > >(
                        azureInfoJsonReader);

                    if (!azureInfo.TryGetValue(accountName, out var accountInfo))
                    {
                        throw new ArgumentException($"Could not find access information for account '{accountName}'!");
                    }

                    StorageCredentials storageCredentials;
                    if (accountInfo.TryGetValue("sas_token", out var sasToken))
                    {
                        storageCredentials = new StorageCredentials(sasToken);
                    }
                    else if (accountInfo.TryGetValue("account_key", out var accountKey))
                    {
                        storageCredentials = new StorageCredentials(accountName: accountName, keyValue: accountKey);
                    }
                    else
                    {
                        throw new ArgumentException(
                                  $"Access to Azure storage account {accountName} requires either account_key or sas_token!");
                    }

                    var storageAccount = new CloudStorageAccount(storageCredentials, useHttps: true, accountName: accountName, endpointSuffix: "core.windows.net");

                    if (accountInfo.TryGetValue("cache_location", out string cacheLocation))
                    {
                        // Replace environment variables in the cache location
                        cacheLocation = Regex.Replace(
                            cacheLocation,
                            "${([^}]+)}",
                            match => Environment.GetEnvironmentVariable(match.Groups[0].Value) ?? match.Value);
                    }

                    this.accountName    = accountName;
                    this.containerName  = containerName;
                    this.cacheLocation  = cacheLocation;
                    blobContainerClient = storageAccount.CreateCloudBlobClient().GetContainerReference(this.containerName);
                    Path = containerPath;
                }
        }
示例#19
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public BlobStorage(StorageCredentials credentials, string containerName = "uploads")
 {
     this.storage       = new CloudStorageAccount(credentials, true);
     this.containerName = containerName;
 }
示例#20
0
        /// <summary>
        /// Constructs a web request to set the ACL for a share.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="publicAccess">The type of public access to allow for the share.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns><returns>A web request to use to perform the operation.</returns></returns>
        public static StorageRequestMessage SetAcl(Uri uri, int?timeout, FileSharePublicAccessType publicAccess, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            StorageRequestMessage request = HttpRequestMessageFactory.SetAcl(uri, timeout, GetShareUriQueryBuilder(), content, operationContext, canonicalizer, credentials);

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
示例#21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudTable"/> class.
 /// </summary>
 /// <param name="tableAbsoluteUri">The absolute URI to the table.</param>
 /// <param name="credentials">The storage account credentials.</param>
 /// <param name="usePathStyleUris">If set to <c>true</c>, use path style Uris.</param>
 internal CloudTable(Uri tableAbsoluteUri, StorageCredentials credentials, bool usePathStyleUris)
     : this(usePathStyleUris, tableAbsoluteUri, credentials)
 {
 }
示例#22
0
        /// <summary>
        /// Constructs a web request to set system properties for a share.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The share's properties.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage SetProperties(Uri uri, int?timeout, FileShareProperties properties, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("properties", properties);

            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            shareBuilder.Add(Constants.QueryConstants.Component, "properties");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, shareBuilder, content, operationContext, canonicalizer, credentials);

            if (properties.Quota.HasValue)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.ShareQuota, properties.Quota.Value);
            }

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
示例#23
0
        /// <summary>
        /// Constructs a web request to return a listing of all shares in this storage account.
        /// </summary>
        /// <param name="uri">The absolute URI for the account.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="listingContext">A set of parameters for the listing operation.</param>
        /// <param name="detailsIncluded">Additional details to return with the listing.</param>
        /// <returns>A web request for the specified operation.</returns>
        public static StorageRequestMessage List(Uri uri, int?timeout, ListingContext listingContext, ShareListingDetails detailsIncluded, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "list");

            if (listingContext != null)
            {
                if (listingContext.Prefix != null)
                {
                    builder.Add("prefix", listingContext.Prefix);
                }

                if (listingContext.Marker != null)
                {
                    builder.Add("marker", listingContext.Marker);
                }

                if (listingContext.MaxResults.HasValue)
                {
                    builder.Add("maxresults", listingContext.MaxResults.ToString());
                }
            }

            if (detailsIncluded != ShareListingDetails.None)
            {
                StringBuilder sb      = new StringBuilder();
                bool          started = false;


                if ((detailsIncluded & ShareListingDetails.Snapshots) == ShareListingDetails.Snapshots)
                {
                    if (!started)
                    {
                        started = true;
                    }
                    else
                    {
                        sb.Append(",");
                    }

                    sb.Append("snapshots");
                }

                if ((detailsIncluded & ShareListingDetails.Metadata) == ShareListingDetails.Metadata)
                {
                    if (!started)
                    {
                        started = true;
                    }
                    else
                    {
                        sb.Append(",");
                    }

                    sb.Append("metadata");
                }

                builder.Add("include", sb.ToString());
            }

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            return(request);
        }
示例#24
0
        private async Task IncrementalCopyAsyncImpl(int overload)
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob source = container.GetPageBlobReference("source");
                await source.CreateAsync(1024);

                string data = new string('a', 512);
                await UploadTextAsync(source, data, Encoding.UTF8);

                CloudPageBlob sourceSnapshot = await source.CreateSnapshotAsync(null, null, null, null);

                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write,
                };

                string sasToken = sourceSnapshot.GetSharedAccessSignature(policy);

                StorageCredentials blobSAS = new StorageCredentials(sasToken);
                Uri sourceSnapshotUri      = blobSAS.TransformUri(TestHelper.Defiddler(sourceSnapshot).SnapshotQualifiedUri);

                StorageCredentials  accountSAS     = new StorageCredentials(sasToken);
                CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, source.ServiceClient.StorageUri, null, null, null);

                CloudPageBlob snapshotWithSas = await accountWithSAS.CreateCloudBlobClient().GetBlobReferenceFromServerAsync(sourceSnapshot.SnapshotQualifiedUri) as CloudPageBlob;

                CloudPageBlob copy   = container.GetPageBlobReference("copy");
                string        copyId = null;
                if (overload == 0)
                {
#if !FACADE_NETCORE
                    copyId = await copy.StartIncrementalCopyAsync(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri));
#else
                    Uri snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    copyId = await copy.StartIncrementalCopyAsync(new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null));
#endif
                }
                else if (overload == 1)
                {
#if !FACADE_NETCORE
                    CloudPageBlob blob = new CloudPageBlob(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri));
#else
                    Uri           snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null);
#endif
                    copyId = await copy.StartIncrementalCopyAsync(blob);
                }
                else if (overload == 2)
                {
#if !FACADE_NETCORE
                    CloudPageBlob blob = new CloudPageBlob(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri));
#else
                    Uri           snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null);
#endif
                    copyId = await copy.StartIncrementalCopyAsync(blob, null, null, null, CancellationToken.None);
                }
                else
                {
#if !FACADE_NETCORE
                    copyId = await copy.StartIncrementalCopyAsync(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri), null, null, null, CancellationToken.None);
#else
                    Uri           snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null);
                    copyId = await copy.StartIncrementalCopyAsync(blob, null, null, null, CancellationToken.None);
#endif
                }

                await WaitForCopyAsync(copy);

                Assert.AreEqual(BlobType.PageBlob, copy.BlobType);
                Assert.AreEqual(CopyStatus.Success, copy.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, copy.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, copy.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, copy.CopyState.BytesCopied);
                Assert.AreEqual(copyId, copy.CopyState.CopyId);
                Assert.IsTrue(copy.Properties.IsIncrementalCopy);
                Assert.IsTrue(copy.CopyState.DestinationSnapshotTime.HasValue);
                Assert.IsTrue(copy.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));
            }
            finally
            {
                container.DeleteIfExistsAsync().Wait();
            }
        }
    private async Task ConvertModel(string modelPath, Stream modelStream = null)
    {
        try
        {
            // Settings
            string       msg;
            const string inputContainerName  = "arrinput";
            const string outputContainerName = "arroutput";

            string modelFile  = Path.GetFileName(modelPath);
            string outputFile = Path.ChangeExtension(modelFile, "arrAsset");

            msg = $"File selected for conversion: {modelPath}\n{modelFile}.";
            AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Info);
            Debug.Log(msg);

            // Default model folder name
            string folderName = string.Empty;

            // ARR Profile
            var loadedProfile = AppServices.RemoteRendering.LoadedProfile;

            // Initialize storage
            var storageAccountData = loadedProfile.StorageAccountData;
            StorageCredentials storageCredentials;

            if (storageAccountData.AuthType == AuthenticationType.AccountKey)
            {
                string authKey = await loadedProfile.StorageAccountData.GetAuthData();

                storageCredentials = new StorageCredentials(loadedProfile.StorageAccountData.StorageAccountName, authKey);
                if (loadedProfile.StorageModelPathByUsername)
                {
                    folderName = AKStorageAccountData.MODEL_PATH_BY_USERNAME_FOLDER;
                }
            }
            else
            {
                string authToken = await loadedProfile.StorageAccountData.GetAuthData();

                storageCredentials = new StorageCredentials(new TokenCredential(authToken));
                if (loadedProfile.StorageModelPathByUsername)
                {
                    folderName = AADAuth.SelectedAccount.Username;
                }
            }
            var storageAccount = new CloudStorageAccount(storageCredentials, loadedProfile.StorageAccountData.StorageAccountName, null, true);

            // Storage client
            var blobClient = storageAccount.CreateCloudBlobClient();

            // Input container
            var inputContainer = blobClient.GetContainerReference(inputContainerName);
            await inputContainer.CreateIfNotExistsAsync();

            // Output container
            var outputContainer = blobClient.GetContainerReference(outputContainerName);
            await outputContainer.CreateIfNotExistsAsync();

            msg = $"Uploading model.";
            AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Info);
            Debug.Log(msg);

            // Upload model
            CloudBlockBlob modelBlockBlob;
            if (loadedProfile.StorageModelPathByUsername)
            {
                var modelFolder = inputContainer.GetDirectoryReference(folderName);
                modelBlockBlob = modelFolder.GetBlockBlobReference(modelFile);
            }
            else
            {
                modelBlockBlob = inputContainer.GetBlockBlobReference(modelFile);
            }

            // Upload using path or provided stream
            if (modelStream == null)
            {
                await modelBlockBlob.UploadFromFileAsync(modelPath);
            }
            else
            {
                await modelBlockBlob.UploadFromStreamAsync(modelStream);
            }

            // Conversion parameters
            string inputUri  = $"https://{loadedProfile.StorageAccountName}.blob.core.windows.net/{inputContainerName}";
            string outputUri = $"https://{loadedProfile.StorageAccountName}.blob.core.windows.net/{outputContainerName}";

            var inputParams  = new AssetConversionInputOptions(inputUri, null, folderName, modelFile);
            var outputParams = new AssetConversionOutputOptions(outputUri, null, folderName, outputFile);
            var options      = AssetConversionOptions.CreateForBlobStorage(null, inputParams, outputParams);

            // Azure authentication
            var client = await loadedProfile.GetClient(loadedProfile.PreferredDomain);

            msg = $"Starting conversion.";
            AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Info);
            Debug.Log(msg);

            // Start conversion
            var   conversion = client.StartAssetConversionAsync(options);
            await conversion;

            string conversionId;

            // Conversion result
            if (conversion.IsCompleted)
            {
                msg = $"Conversion started.";
                AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Info);
                Debug.Log(msg);
                conversionId = conversion.Result.ConversionUuid;
            }
            else
            {
                msg = $"Error starting conversion.";
                AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Error);
                Debug.LogError(msg);
                return;
            }

            // Poll conversion process
            while (true)
            {
                // Wait 10 seconds
                await Task.Delay(10000);

                // Poll conversion status
                var task = await client.GetAssetConversionStatusAsync(conversionId);

                ConversionSessionStatus status = task.Result;
                if (status == ConversionSessionStatus.Created || status == ConversionSessionStatus.Running)
                {
                    // In progress
                    msg = $"Conversion Session In Progress...";
                    AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Info);
                    Debug.Log(msg);
                }
                else
                {
                    // Done, success/fail
                    switch (status)
                    {
                    case ConversionSessionStatus.Unknown:
                    case ConversionSessionStatus.Aborted:
                    case ConversionSessionStatus.Failure:
                        msg = $"Conversion Session Failed.";
                        AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Error);
                        Debug.LogError(msg);
                        break;

                    case ConversionSessionStatus.Success:
                        msg = $"Conversion Session Completed Successfully.";
                        AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Info);
                        OnModelConversionSuccess?.Invoke();
                        Debug.Log(msg);
                        break;
                    }

                    break;
                }
            }
        }
        catch (Exception e)
        {
            var msg = $"Conversion Process Failed.\n{e}";
            AppServices.AppNotificationService.RaiseNotification(msg, AppNotificationType.Error);
            Debug.LogError(msg);
            Debug.LogError(e.StackTrace);
        }
    }
示例#26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AzureQueueFabricBridge"/> class.
 /// Which is used to provides connectivity using the Azure Storage Queue.
 /// </summary>
 public AzureQueueFabricBridge(StorageCredentials credentials)
 {
     Credentials = credentials;
 }
示例#27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudTable"/> class.
 /// </summary>
 /// <param name="tableAbsoluteUri">The absolute URI to the table.</param>
 /// <param name="credentials">The account credentials.</param>
 public CloudTable(Uri tableAbsoluteUri, StorageCredentials credentials)
     : this(null, tableAbsoluteUri, credentials)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlobContainer"/> class.
 /// </summary>
 /// <param name="containerAddress">The absolute URI to the container.</param>
 /// <param name="credentials">The account credentials.</param>
 public CloudBlobContainer(string containerAddress, StorageCredentials credentials)
     : this(containerAddress, new CloudBlobClient(NavigationHelper.GetServiceClientBaseAddress(containerAddress, null), credentials))
 {
 }
 /// <summary>
 /// Initializes log4net with azure table logging.
 /// </summary>
 public static void InitializeAzureTableLogging(StorageCredentials credentials, string customTable = null, Level logLevel = null)
 {
     if (credentials.AccountName.StartsWith("devstoreaccount"))
         InitializeAzureTableLogging(CloudStorageAccount.DevelopmentStorageAccount, customTable, logLevel);
     else
         InitializeAzureTableLogging(new CloudStorageAccount(credentials, true), customTable, logLevel);
 }
示例#30
0
 internal static void CheckAllowInsecureEndpoints(bool allowInsecureRemoteEndpoints, StorageCredentials info, Uri baseUri)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     if (allowInsecureRemoteEndpoints)
     {
         return;
     }
     if (baseUri == null || string.IsNullOrEmpty(baseUri.Scheme))
     {
         throw new SecurityException("allowInsecureRemoteEndpoints is set to false (default setting) but the endpoint URL seems to be empty or there is no URL scheme." +
                                     "Please configure the provider to use an https endpoint for the storage endpoint or " +
                                     "explicitly set the configuration option allowInsecureRemoteEndpoints to true.");
     }
     if (baseUri.Scheme.ToUpper(CultureInfo.InvariantCulture) == Uri.UriSchemeHttps.ToUpper(CultureInfo.InvariantCulture))
     {
         return;
     }
     if (baseUri.IsLoopback)
     {
         return;
     }
     throw new SecurityException("The provider is configured with allowInsecureRemoteEndpoints set to false (default setting) but the endpoint for " +
                                 "the storage system does not seem to be an https or local endpoint. " +
                                 "Please configure the provider to use an https endpoint for the storage endpoint or " +
                                 "explicitly set the configuration option allowInsecureRemoteEndpoints to true.");
 }
示例#31
0
        /// <summary>
        /// Constructs a web request to get the stats of the service.
        /// </summary>
        /// <param name="uri">The absolute URI to the service.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <returns>A StorageRequestMessage to get the service stats.</returns>
        public static StorageRequestMessage GetStats(Uri uri, int?timeout, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            shareBuilder.Add(Constants.QueryConstants.Component, "stats");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, shareBuilder, null /* content */, operationContext, canonicalizer, credentials);

            return(request);
        }
示例#32
0
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <ProgenyDbContext>(options =>
                                                     options.UseSqlServer(Configuration["ProgenyDefaultConnection"],
                                                                          sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
            }));

            services.AddDbContext <WebDbContext>(options =>
                                                 options.UseSqlServer(Configuration["WebDefaultConnection"],
                                                                      sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
            }));


            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration["DataProtectionConnection"],
                                                                              sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
            }));

            services.AddDbContext <MediaDbContext>(options =>
                                                   options.UseSqlServer(Configuration["MediaDefaultConnection"],
                                                                        sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
            }));

            var                credentials = new StorageCredentials(Constants.CloudBlobUsername, Configuration["BlobStorageKey"]);
            CloudBlobClient    blobClient  = new CloudBlobClient(new Uri(Constants.CloudBlobBase), credentials);
            CloudBlobContainer container   = blobClient.GetContainerReference("dataprotection");

            container.CreateIfNotExistsAsync().GetAwaiter().GetResult();

            services.AddDataProtection()
            .SetApplicationName("KinaUnaWebApp")
            .PersistKeysToAzureBlobStorage(container, "kukeys.xml");

            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireDigit           = false;
                options.SignIn.RequireConfirmedEmail    = true;
                options.User.RequireUniqueEmail         = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <DataProtectionTokenProviderOptions>(options =>
            {
                options.TokenLifespan = TimeSpan.FromDays(90);
            });

            services.AddTransient <ILoginService <ApplicationUser>, EfLoginService>();
            services.AddTransient <IRedirectService, RedirectService>();
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddLocalization(o =>
            {
                o.ResourcesPath = "Resources";
            });

            X509Certificate2 cert = null;

            using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                certStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certCollection = certStore.Certificates.Find(
                    X509FindType.FindByThumbprint,
                    Configuration["X509ThumbPrint"],
                    false);
                // Get the first cert with the thumbprint
                if (certCollection.Count > 0)
                {
                    cert = certCollection[0];
                }
            }

            if (_env.IsDevelopment())
            {
                services.AddCors(options =>
                {
                    options.AddPolicy("KinaUnaCors",
                                      builder =>
                    {
                        builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                    });
                });
            }
            else
            {
                services.AddCors(options =>
                {
                    options.AddDefaultPolicy(builder =>
                    {
                        builder.WithOrigins(Constants.WebAppUrl, "https://" + Constants.AppRootDomain);
                    });
                    options.AddPolicy("KinaUnaCors",
                                      builder =>
                    {
                        builder.WithOrigins("https://*." + Constants.AppRootDomain).SetIsOriginAllowedToAllowWildcardSubdomains().AllowAnyHeader().AllowAnyMethod().AllowCredentials();
                    });
                });
            }


            services.AddControllersWithViews()
            .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix);

            services.AddIdentityServer(x =>
            {
                x.Authentication.CookieLifetime          = TimeSpan.FromDays(90);
                x.Authentication.CookieSlidingExpiration = true;
            })
            .AddSigningCredential(cert)
            .AddAspNetIdentity <ApplicationUser>()
            // This adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(Configuration["AuthDefaultConnection"],
                                                                  sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            // This adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(Configuration["AuthDefaultConnection"],
                                                                  sql => sql.MigrationsAssembly(migrationsAssembly));

                // This enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 3600;
            })
            .AddRedisCaching(options =>
            {
                options.RedisConnectionString = Configuration["RedisConnection"];
                options.KeyPrefix             = Constants.AppName + "idp";
            })
            .AddClientStoreCache <IdentityServer4.EntityFramework.Stores.ClientStore>()
            .AddResourceStoreCache <IdentityServer4.EntityFramework.Stores.ResourceStore>()
            .AddCorsPolicyCache <IdentityServer4.EntityFramework.Services.CorsPolicyService>()
            .AddProfileServiceCache <ProfileService>()
            .Services.AddTransient <IProfileService, ProfileService>();

            services.AddAuthentication().AddGoogle("Google", "Google", options =>
            {
                options.ClientId     = Configuration["GoogleClientId"];
                options.ClientSecret = Configuration["GoogleClientSecret"];
            }).AddFacebook("Facebook", "Facebook", options =>
            {
                options.ClientId     = Configuration["FacebookClientId"];
                options.ClientSecret = Configuration["FacebookClientSecret"];
            }).AddMicrosoftAccount("Microsoft", "Microsoft", microsoftOptions =>
            {
                microsoftOptions.ClientId     = Configuration["MicrosoftClientId"];
                microsoftOptions.ClientSecret = Configuration["MicrosoftClientSecret"];
            });

            services.AddApplicationInsightsTelemetry();
        }
示例#33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlobContainer"/> class.
 /// </summary>
 /// <param name="containerAddress">A <see cref="System.Uri"/> object specifying the absolute URI to the container.</param>
 /// <param name="credentials">A <see cref="StorageCredentials"/> object.</param>
 public CloudBlobContainer(Uri containerAddress, StorageCredentials credentials)
     : this(new StorageUri(containerAddress), credentials)
 {
 }
示例#34
0
        /// <summary>
        /// Constructs a web request to create a snapshot of a share.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Snapshot(Uri uri, int?timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.ResourceType, "share");
            builder.Add(Constants.QueryConstants.Component, Constants.QueryConstants.Snapshot);

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
示例#35
0
        /// <summary>
        /// Constructs a web request to create a new share.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="properties">Properties to set on the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Create(Uri uri, FileShareProperties properties, int?timeout, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            StorageRequestMessage request = HttpRequestMessageFactory.Create(uri, timeout, shareBuilder, content, operationContext, canonicalizer, credentials);

            if (properties != null && properties.Quota.HasValue)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.ShareQuota, properties.Quota.Value);
            }

            return(request);
        }
示例#36
0
        /// <summary>
        /// Constructs a web request to delete the share and all of the files within it.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="snapshot">A <see cref="DateTimeOffset"/> specifying the snapshot timestamp, if the share is a snapshot.</param>

        /// <param name="deleteSnapshotsOption">A <see cref="DeleteShareSnapshotsOption"/> object indicating whether to only delete the share or delete the share and all snapshots.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Delete(Uri uri, int?timeout, DateTimeOffset?snapshot, DeleteShareSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            ShareHttpRequestMessageFactory.AddShareSnapshot(shareBuilder, snapshot);
            StorageRequestMessage request = HttpRequestMessageFactory.Delete(uri, timeout, shareBuilder, content, operationContext, canonicalizer, credentials);

            switch (deleteSnapshotsOption)
            {
            case DeleteShareSnapshotsOption.None:
                break;     // nop

            case DeleteShareSnapshotsOption.IncludeSnapshots:
                request.Headers.Add(
                    Constants.HeaderConstants.DeleteSnapshotHeader,
                    Constants.HeaderConstants.IncludeSnapshotsValue);
                break;
            }

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using an absolute URI to the blob.
 /// </summary>
 /// <param name="blobAbsoluteUri">The absolute URI to the blob.</param>
 /// <param name="credentials">The account credentials.</param>
 /// <param name="usePathStyleUris"><c>True</c> to use path-style URIs; otherwise, <c>false</c>.</param>
 public CloudBlockBlob(string blobAbsoluteUri, StorageCredentials credentials, bool usePathStyleUris)
     : base(blobAbsoluteUri, credentials, usePathStyleUris)
 {
     this.Properties.BlobType = BlobType.BlockBlob;
 }
示例#38
0
        /// <summary>
        /// Generates a web request to return the user-defined metadata for this share.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="snapshot">A <see cref="DateTimeOffset"/> specifying the snapshot timestamp, if the share is a snapshot.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage GetMetadata(Uri uri, int?timeout, DateTimeOffset?snapshot, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            ShareHttpRequestMessageFactory.AddShareSnapshot(shareBuilder, snapshot);

            StorageRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, shareBuilder, content, operationContext, canonicalizer, credentials);

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudFileShare"/> class.
 /// </summary>
 /// <param name="shareAddress">The absolute URI to the share.</param>
 /// <param name="credentials">A <see cref="StorageCredentials"/> object.</param>
 public CloudFileShare(Uri shareAddress, StorageCredentials credentials)
     : this(new StorageUri(shareAddress), credentials)
 {
 }
        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>Task<returns>
        private static async Task BasicStorageBlockBlobOperationsWithAccountSASAsync()
        {
            const string imageToUpload = "HelloWorld.png";
            string blockBlobContainerName = "demoblockblobcontainer-" + Guid.NewGuid();

            // Call GetAccountSASToken to get a sasToken based on the Storage Account Key
            string sasToken = GetAccountSASToken();
          
            // Create an AccountSAS from the SASToken
            StorageCredentials accountSAS = new StorageCredentials(sasToken);

            //Informational: Print the Account SAS Signature and Token
            Console.WriteLine();
            Console.WriteLine("Account SAS Signature: " + accountSAS.SASSignature);
            Console.WriteLine("Account SAS Token: " + accountSAS.SASToken);
            Console.WriteLine();
            
            // Create a container for organizing blobs within the storage account.
            Console.WriteLine("1. Creating Container using Account SAS");

            // Get the Container Uri  by passing the Storage Account and the container Name
            Uri ContainerUri = GetContainerSASUri(blockBlobContainerName);

            // Create a CloudBlobContainer by using the Uri and the sasToken
            CloudBlobContainer container = new CloudBlobContainer(ContainerUri, new StorageCredentials(sasToken));
            try
            {
                await container.CreateIfNotExistsAsync();
            }
            catch (StorageException)
            {
                Console.WriteLine("If you are running with the default configuration please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                Console.ReadLine();
                throw;
            }

            // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate 
            // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions 
            // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the image 
            // using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/democontainer/HelloWorld.png
            // await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            // Upload a BlockBlob to the newly created container
            Console.WriteLine("2. Uploading BlockBlob");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(imageToUpload);
            await blockBlob.UploadFromFileAsync(imageToUpload, FileMode.Open);

            // List all the blobs in the container 
            Console.WriteLine("3. List Blobs in Container");
            foreach (IListBlobItem blob in container.ListBlobs())
            {
                // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
                // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type
                Console.WriteLine("- {0} (type: {1})", blob.Uri, blob.GetType());
            }

            // Download a blob to your file system
            Console.WriteLine("4. Download Blob from {0}", blockBlob.Uri.AbsoluteUri);
            await blockBlob.DownloadToFileAsync(string.Format("./CopyOf{0}", imageToUpload), FileMode.Create);

            // Create a read-only snapshot of the blob
            Console.WriteLine("5. Create a read-only snapshot of the blob");
            CloudBlockBlob blockBlobSnapshot = await blockBlob.CreateSnapshotAsync(null, null, null, null);

            // Clean up after the demo 
            Console.WriteLine("6. Delete block Blob and all of its snapshots");
            await blockBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);

            Console.WriteLine("7. Delete Container");
            await container.DeleteIfExistsAsync();

        }
        /// <summary>
        /// Gets connection string of the given storage service name.
        /// </summary>
        /// <param name="name">The storage service name</param>
        /// <returns>The connection string</returns>
        public string GetStorageServiceConnectionString(string name)
        {
            StorageServiceGetResponse storageService;
            StorageAccountGetKeysResponse storageKeys;

            try
            {
                storageService = StorageClient.StorageAccounts.Get(name);
                storageKeys = StorageClient.StorageAccounts.GetKeys(name);
            }
            catch
            {
                throw new Exception(string.Format(Resources.StorageAccountNotFound, name));
            }

            Debug.Assert(storageService.ServiceName != null);
            Debug.Assert(storageKeys != null);

            StorageCredentials credentials = new StorageCredentials(
                storageService.ServiceName,
                storageKeys.PrimaryKey);

            CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(
                credentials,
                General.CreateHttpsEndpoint(storageService.Properties.Endpoints[0].ToString()),
                General.CreateHttpsEndpoint(storageService.Properties.Endpoints[1].ToString()),
                General.CreateHttpsEndpoint(storageService.Properties.Endpoints[2].ToString())
                );

            return cloudStorageAccount.ToString(true);
        }
示例#42
0
 public StorageRequestMessage(HttpMethod method, Uri requestUri, ICanonicalizer canonicalizer, StorageCredentials credentials, string accountName)
     : base(method, requestUri)
 {
     this.Canonicalizer = canonicalizer;
     this.Credentials   = credentials;
     this.AccountName   = accountName;
 }
 public ViewDataContext(string baseAddress, StorageCredentials credentials)
     : base(baseAddress, credentials)
 {
 }
示例#44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlob"/> class creating a new service client.
 /// </summary>
 /// <param name="blobAbsoluteUri">Complete Uri.</param>
 /// <param name="credentials">Storage credentials.</param>
 /// <param name="usePathStyleUris">True to use path style Uris.</param>
 internal CloudBlob(string blobAbsoluteUri, StorageCredentials credentials, bool usePathStyleUris)
     : this(blobAbsoluteUri, new CloudBlobClient(NavigationHelper.GetServiceClientBaseAddress(blobAbsoluteUri, usePathStyleUris), credentials))
 {
 }
示例#45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudQueue"/> class.
 /// </summary>
 /// <param name="address">The absolute URI to the queue.</param>
 /// <param name="credentials">The account credentials.</param>
 public CloudQueue(string address, StorageCredentials credentials)
     : this(null, address, credentials)
 {
 }
示例#46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudPageBlob"/> class.
 /// </summary>
 /// <param name="blobAddress">The blob address.</param>
 /// <param name="credentials">The credentials.</param>
 /// <param name="usePathStyleUris">If set to <c>true</c>, use path style Uris.</param>
 internal CloudPageBlob(string blobAddress, StorageCredentials credentials, bool usePathStyleUris)
     : base(blobAddress, credentials, usePathStyleUris)
 {
     this.Properties.BlobType = BlobType.PageBlob;
 }
示例#47
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudAnalyticsClient"/> class using the specified Blob and Table service endpoints
        /// and account credentials.
        /// </summary>
        /// <param name="blobStorageUri">A <see cref="StorageUri"/> object containing the Blob service endpoint to use to create the client.</param>
        /// <param name="tableStorageUri">A <see cref="StorageUri"/> object containing the Table service endpoint to use to create the client.</param>
        /// <param name="credentials">A <see cref="StorageCredentials"/> object.</param>
        public CloudAnalyticsClient(StorageUri blobStorageUri, StorageUri tableStorageUri, StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("blobStorageUri", blobStorageUri);
            CommonUtility.AssertNotNull("tableStorageUri", tableStorageUri);

            this.blobClient   = new CloudBlobClient(blobStorageUri, credentials);
            this.tableClient  = new CloudTableClient(tableStorageUri, credentials);
            this.LogContainer = Constants.AnalyticsConstants.LogsContainer;
        }
示例#48
0
        private static async Task TestAccessAsync(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, ICloudBlob blob)
        {
            OperationContext   operationContext = new OperationContext();
            StorageCredentials credentials      = string.IsNullOrEmpty(sasToken) ?
                                                  new StorageCredentials() :
                                                  new StorageCredentials(sasToken);

            if (container != null)
            {
                container = new CloudBlobContainer(container.Uri, credentials);
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = container.GetBlockBlobReference(blob.Name);
                }
                else
                {
                    blob = container.GetPageBlobReference(blob.Name);
                }
            }
            else
            {
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = new CloudBlockBlob(blob.Uri, credentials);
                }
                else
                {
                    blob = new CloudPageBlob(blob.Uri, credentials);
                }
            }

            if (container != null)
            {
                if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List)
                {
                    await container.ListBlobsSegmentedAsync(null);
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync(
                        async() => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.None, null, null, null, operationContext),
                        operationContext,
                        "List blobs while SAS does not allow for listing",
                        HttpStatusCode.NotFound);
                }
            }

            if ((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read)
            {
                await blob.FetchAttributesAsync();

                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, blob.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, blob.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, blob.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, blob.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, blob.Properties.ContentType);
                    }
                }
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.FetchAttributesAsync(null, null, operationContext),
                    operationContext,
                    "Fetch blob attributes while SAS does not allow for reading",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
            {
                await blob.SetMetadataAsync();
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(null, null, operationContext),
                    operationContext,
                    "Set blob metadata while SAS does not allow for writing",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete)
            {
                await blob.DeleteAsync();
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.DeleteAsync(DeleteSnapshotsOption.None, null, null, operationContext),
                    operationContext,
                    "Delete blob while SAS does not allow for deleting",
                    HttpStatusCode.NotFound);
            }
        }
 public SharedKeyAuthenticationHttpHandler(ICanonicalizer canonicalizer, StorageCredentials credentials, string accountName)
 {
     this.canonicalizer = canonicalizer;
     this.credentials = credentials;
     this.accountName = accountName;
 }
示例#50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudQueue"/> class.
 /// </summary>
 /// <param name="queueAddress">The absolute URI to the queue.</param>
 /// <param name="credentials">The account credentials.</param>
 public CloudQueue(Uri queueAddress, StorageCredentials credentials)
 {
     this.ParseQueryAndVerify(queueAddress, credentials);
     this.Metadata      = new Dictionary <string, string>();
     this.EncodeMessage = true;
 }
示例#51
0
        private void SetupCommands()
        {
            Add_Patient = new DelegateCommand(async () =>
               {
                   Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 2);
           
                   MessageDialog mm = new MessageDialog("mission Started");
                   //await mm.ShowAsync();

                   // Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 2);

                   if (string.IsNullOrWhiteSpace(Pa.FName) ||
                      string.IsNullOrWhiteSpace(Pa.LName) ||
                      string.IsNullOrWhiteSpace(Pa.Gender) ||
                      string.IsNullOrWhiteSpace(Pa.MaritalStatus) ||
                      string.IsNullOrWhiteSpace(Pa.SocialID) ||
                      string.IsNullOrWhiteSpace(Pa.Email) ||
                      string.IsNullOrWhiteSpace(Pa.Phone))
                   {
                       //show message
                       mm = new MessageDialog("Please fill in all the fields");
                       await mm.ShowAsync();
                       return;
                   }

                  // Pa.Dob = Convert.ToDateTime(String.Format("{0:d}", Pa.Dob));
                   switch (Pa.Gender)
                   {
                       case "0":
                           Pa.Gender = "Male";
                           break;

                       case "1":
                           Pa.Gender = "Female";
                           break;
                   }

                   switch (Pa.MaritalStatus)
                   {
                       case "0":
                           Pa.MaritalStatus = "Single";
                           break;

                       case "1":
                           Pa.MaritalStatus = "Married";
                           break;
                   }

                   /////////////////////////////////////////////////////////////// save the image
                   string errorString = string.Empty;

                   if (media != null)
                   {
                       // Set blob properties of TodoItem.
                       Pa.ContainerName = "patientimagestorageimages";
                       Pa.ResourceName = media.Name;
                   }
                   else
                   {
                       if( Pa.Gender == "Male"){

                           var uri = new Uri("ms-appx:///Assets/Administrator-icon.png");

                           media = await StorageFile.GetFileFromApplicationUriAsync(uri);

                           Pa.ContainerName = "patientimagestorageimages";
                           Pa.ResourceName = media.Name;
                       }
                       else
                       {
                           var uri = new Uri("ms-appx:///Assets/Office-Girl-icon.png");

                           media = await StorageFile.GetFileFromApplicationUriAsync(uri);

                           Pa.ContainerName = "patientimagestorageimages";
                           Pa.ResourceName = media.Name;
                       }
                   }
                  



                   /////////////////////////////////////////////////////////////////
                   try
                   {
                       await patientsTable.InsertAsync(Pa);
                   }
                   catch (Exception e)
                   {
                       mm = new MessageDialog("error occured");
                       mm.ShowAsync();
                   }

                   //if (media != null)
                   //{
                   if (!string.IsNullOrEmpty(Pa.SasQueryString))
                   {
                       using (var fileStream = await media.OpenStreamForReadAsync())
                       {
                           StorageCredentials cred = new StorageCredentials(Pa.SasQueryString);
                           var imageUri = new Uri(Pa.ImageUri);
                           CloudBlobContainer container = new CloudBlobContainer(
                       new Uri(string.Format("https://{0}/{1}",
                           imageUri.Host, Pa.ContainerName)), cred);

                           // Upload the new image as a BLOB from the stream.
                           CloudBlockBlob blobFromSASCredential =
                               container.GetBlockBlobReference(Pa.ResourceName);
                           await blobFromSASCredential.UploadFromStreamAsync(fileStream.AsInputStream());
                       }
                   }
                   //}

                   /////////////////////////////////////////////////////////////////
                   MessageDialog m = new MessageDialog("Mission Done");
                  // await m.ShowAsync();

                   //  Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 2);


                   ShowAddPatientTemplate = false;
                   NotDisplayPatientForm = true;

                   DisplayRegistrationColor = "LightGray";

                   createPatient();
                 RefreshFlag = !RefreshFlag;
                 media = null;

                 Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 2);
           
               }, true);


            Cancel_Add_Patient = new DelegateCommand(() =>
           {
               ShowAddPatientTemplate = false;
               NotDisplayPatientForm = true;
               DisplayRegistrationColor = "LightGray";
               createPatient();

           }, true);


            PhotoPicker = new DelegateCommand(async () =>
            {


                FileOpenPicker open = new FileOpenPicker();
                open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                open.ViewMode = PickerViewMode.Thumbnail;

                // Filter to include a sample subset of file types
                open.FileTypeFilter.Clear();
                open.FileTypeFilter.Add(".bmp");
                open.FileTypeFilter.Add(".png");
                open.FileTypeFilter.Add(".jpeg");
                open.FileTypeFilter.Add(".jpg");

                media = await open.PickSingleFileAsync();


                if (media != null)
                {
                    // Ensure the stream is disposed once the image is loaded
                    FileStream = await media.OpenAsync(Windows.Storage.FileAccessMode.Read);


                    await MybitmapImage.SetSourceAsync(FileStream);


                    //BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
                    //PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
                    //Pa.patientImage= pixelData.DetachPixelData();




                }
                open = null;
                // createPatient();
            }, true);


            Add_Patient_Info = new DelegateCommand(async () =>
            {

            //   await new MessageDialog("Adding info").ShowAsync();

             //  await new MessageDialog(ComboPatient).ShowAsync();
               try
               {
                  // Pi.PatientId = (await patientsTable.Where(p => p.FName == ComboPatient).Select(patient => patient.PatientID).ToListAsync()).First();
                   string ln = ComboPatient.Substring(0, ComboPatient.IndexOf(","));
                   string fn = ComboPatient.Substring(ComboPatient.IndexOf(",") + 2);
                   Pi.PatientId = (await patientsTable.Where(p => (p.LName == (ln) && p.FName == (fn))).Select(patient => patient.PatientID).ToListAsync()).First();

               }
               catch(Exception e)
               {
                   new MessageDialog(e.Message).ShowAsync();
                   return;
               }
               try
               {
                   await patientsInfoTable.InsertAsync(Pi);
               }
                //catch (WebException webEx)
                //{
                //    string errorDetail = string.Empty;
                //    using (StreamReader streamReader = new StreamReader(webEx.Response.GetResponseStream(), true))
                //    {
                //        errorDetail = streamReader.ReadToEnd();
                //    }
                //}

               catch (Exception e)
               {
                   new MessageDialog(e.Message).ShowAsync();
                   return;
               }

                //await new MessageDialog("finished Adding info").ShowAsync();
                ShowAddPatientInfoTemplate = false;
                NotDisplayPatientForm = true;

                DisplayRegistrationColor = "LightGray";

                createPatientHistory();
                RefreshFlag2 = !RefreshFlag2;
                

            }, true);

            Cancel_Add_Patient_Info = new DelegateCommand(async () =>
            {
                ShowAddPatientInfoTemplate = false;
                NotDisplayPatientForm = true;

                DisplayRegistrationColor = "LightGray";

                createPatientHistory();

            }, true);

            Add_Patient_Document = new DelegateCommand(async () =>
            {

                Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 2);
           
                if (string.IsNullOrWhiteSpace(ComboPatient) ||string.IsNullOrWhiteSpace(SelectedFile))
                      
                {
                    //show message
                    MessageDialog m = new MessageDialog("Please fill in all the fields");
                    await m.ShowAsync();
                    return;
                }
                //await new MessageDialog("Adding info").ShowAsync();
                //await new MessageDialog(ComboPatient).ShowAsync();
                string ln = ComboPatient.Substring(0, ComboPatient.IndexOf(","));
                string fn = ComboPatient.Substring(ComboPatient.IndexOf(",")+2);
                Pd.PatientID = (await patientsTable.Where(p =>( p.LName==(ln ) && p.FName==(fn) )).Select(patient => patient.PatientID).ToListAsync()).First();


                if (media != null)
                {
                    // Set blob properties of TodoItem.
                    Pd.ContainerName = "patientimagestorageimages";
                    Pd.ResourceName = media.Name;
                }

                Pd.CreatedAt = DateTime.Now;

                string temp = (Pd.ResourceName).Substring(Pd.ResourceName.IndexOf("."));

                switch (temp)
                {
                    case ".pdf": Pd.FileTypeImage = "Assets/FileType-Pdf-icon.png";
                        break;
                    case ".txt": Pd.FileTypeImage = "Assets/FileType-Txt-icon.png";
                        break;
                    case ".doc": Pd.FileTypeImage = "Assets/FileType-Doc-icon.png";
                        break;
                    case ".xls": Pd.FileTypeImage = "Assets/FileType-Xls-icon.png";
                        break;
                    case ".docx": Pd.FileTypeImage = "Assets/FileType-Doc-icon.png";
                        break;
                    case ".xlsx": Pd.FileTypeImage = "Assets/FileType-Xls-icon.png";
                        break;

                    default:    Pd.FileTypeImage = "Assets/Basic-Document-icon.png";
                        break;
                
                }

                try
                {
                    await patientsDocumentTable.InsertAsync(Pd);
                }
                catch (Exception e)
                {
                    new MessageDialog("Sorry file couldn't be found.").ShowAsync();
                    Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 2);
           
                    return;
                }

                if (!string.IsNullOrEmpty(Pd.SasQueryString))
                {
                    using (var fileStream = await media.OpenStreamForReadAsync())
                    {
                        

                        StorageCredentials cred = new StorageCredentials(Pd.SasQueryString);
                        var imageUri = new Uri(Pd.ImageUri);
                        CloudBlobContainer container = new CloudBlobContainer(
                    new Uri(string.Format("https://{0}/{1}",
                        imageUri.Host, Pd.ContainerName)), cred);

                     

                        // Upload the new image as a BLOB from the stream.
                        CloudBlockBlob blobFromSASCredential = container.GetBlockBlobReference(Pd.ResourceName);
                        await blobFromSASCredential.UploadFromStreamAsync(fileStream.AsInputStream());
                    }
                }
              
                /////////////////////////////////////////////////////////////////
                  //new MessageDialog("Mission Done").ShowAsync();


                ShowAddPatientDocumentTemplate = false;
                NotDisplayPatientForm = true;

                DisplayRegistrationColor = "LightGray";

                Pd = null;
                createPatientDocument();
                
                media = null;
                SelectedFile =null;
                RefreshFlag2 = !RefreshFlag2;
                Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 2);
           
            }, true);


            Cancel_Add_Patient_Document = new DelegateCommand(async () =>
            {
                ShowAddPatientDocumentTemplate = false;
                NotDisplayPatientForm = true;

                DisplayRegistrationColor = "LightGray";

                Pd = null;
                createPatientDocument();
                
                media = null;
                SelectedFile = null;
            }, true);


            FilePicker = new DelegateCommand(async () =>
            {


                FileOpenPicker open = new FileOpenPicker();
                open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                open.ViewMode = PickerViewMode.Thumbnail;

                // Filter to include a sample subset of file types
                open.FileTypeFilter.Clear();
                open.FileTypeFilter.Add(".pdf");
                open.FileTypeFilter.Add(".doc");
                open.FileTypeFilter.Add(".docx");
                open.FileTypeFilter.Add(".txt");
                open.FileTypeFilter.Add(".xls");
                open.FileTypeFilter.Add(".xlsx");
                open.FileTypeFilter.Add(".bmp");
                open.FileTypeFilter.Add(".png");
                open.FileTypeFilter.Add(".jpeg");
                open.FileTypeFilter.Add(".jpg");
               

                media = await open.PickSingleFileAsync();


                if (media != null)
                {
                    // Ensure the stream is disposed once the image is loaded
                    FileStream = await media.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    SelectedFile = media.Name;
                    if(SelectedFile.Contains(" "))
                    {
                        new MessageDialog("please remove the spaces from the original file name then re-select it.").ShowAsync();
                        return;
                    }

                }
                open = null;
              
            }, true);
        }
示例#52
0
 public CustomerDataContext(string baseAddress, StorageCredentials credentials) :
     base(baseAddress, credentials)
 {
 }
示例#53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlob"/> class using an absolute URI to the blob, and the snapshot timestamp,
 /// if the blob is a snapshot.
 /// </summary>
 /// <param name="blobAbsoluteUri">The absolute URI to the blob.</param>
 /// <param name="snapshotTime">The snapshot timestamp, if the blob is a snapshot.</param>
 /// <param name="credentials">The account credentials.</param>
 public CloudBlob(string blobAbsoluteUri, DateTime? snapshotTime, StorageCredentials credentials)
     : this(blobAbsoluteUri, snapshotTime, new CloudBlobClient(NavigationHelper.GetServiceClientBaseAddress(blobAbsoluteUri, null), credentials))
 {
 }
        public void TableSASConstructors()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                TableServiceContext context = tableClient.GetTableServiceContext();
                context.AddObject(table.Name, new BaseEntity("PK", "RK"));
                context.SaveChangesWithRetries();

                // Prepare SAS authentication with full permissions
                string sasToken = table.GetSharedAccessSignature(
                    new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query,
                    SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30)
                },
                    null /* accessPolicyIdentifier */,
                    null /* startPk */,
                    null /* startRk */,
                    null /* endPk */,
                    null /* endRk */);

                CloudStorageAccount sasAccount;
                StorageCredentials  sasCreds;
                CloudTableClient    sasClient;
                CloudTable          sasTable;
                TableServiceContext sasContext;
                Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint);
                int count;

                // SAS via connection string parse
                sasAccount = CloudStorageAccount.Parse(string.Format("TableEndpoint={0};SharedAccessSignature={1}", baseUri.AbsoluteUri, sasToken));
                sasClient  = sasAccount.CreateCloudTableClient();
                sasTable   = sasClient.GetTableReference(table.Name);
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);

                // SAS via account constructor
                sasCreds   = new StorageCredentials(sasToken);
                sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri);
                sasClient  = sasAccount.CreateCloudTableClient();
                sasTable   = sasClient.GetTableReference(table.Name);
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);

                // SAS via client constructor URI + Creds
                sasCreds   = new StorageCredentials(sasToken);
                sasClient  = new CloudTableClient(baseUri, sasCreds);
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);

                // SAS via CloudTable constructor Uri + Client
                sasCreds   = new StorageCredentials(sasToken);
                sasTable   = new CloudTable(table.Uri, tableClient);
                sasClient  = sasTable.ServiceClient;
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
示例#55
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudPageBlob"/> class using an absolute URI to the blob.
 /// </summary>
 /// <param name="blobAddress">The absolute URI to the blob.</param>
 /// <param name="credentials">The account credentials.</param>
 public CloudPageBlob(string blobAddress, StorageCredentials credentials)
     : base(blobAddress, credentials)
 {
     this.Properties.BlobType = BlobType.PageBlob;
 }
示例#56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlob"/> class using an absolute URI to the blob.
 /// </summary>
 /// <param name="blobAbsoluteUri">A <see cref="System.Uri"/> specifying the absolute URI to the blob.</param>
 /// <param name="snapshotTime">A <see cref="DateTimeOffset"/> specifying the snapshot timestamp, if the blob is a snapshot.</param>
 /// <param name="credentials">A <see cref="StorageCredentials"/> object.</param>
 public CloudBlob(Uri blobAbsoluteUri, DateTimeOffset?snapshotTime, StorageCredentials credentials)
     : this(new StorageUri(blobAbsoluteUri), snapshotTime, credentials)
 {
 }
示例#57
0
 public EventualCloudTableClient(StorageUri storageUri, StorageCredentials credentials) : base(storageUri, credentials)
 {
 }
示例#58
0
        //Private Methods
        private void ValidateParameters()
        {
            if (string.IsNullOrEmpty(ArchiveBlobName))
            {
                if (ConfigurationName != null || ConfigurationArgument != null ||
                    ConfigurationData != null)
                {
                    this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters);
                }
                if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null)
                {
                    this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoStorageParameters);
                }
            }
            else
            {
                if (string.Compare(
                        Path.GetFileName(ArchiveBlobName),
                        ArchiveBlobName,
                        StringComparison.InvariantCultureIgnoreCase) != 0)
                {
                    this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath);
                }

                if (ConfigurationData != null)
                {
                    ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData);

                    if (!File.Exists(ConfigurationData))
                    {
                        this.ThrowInvalidArgumentError(
                            Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscCannotFindConfigurationDataFile,
                            ConfigurationData);
                    }
                    if (string.Compare(
                            Path.GetExtension(ConfigurationData),
                            ".psd1",
                            StringComparison.InvariantCultureIgnoreCase) != 0)
                    {
                        this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscInvalidConfigurationDataFile);
                    }
                }

                if (ArchiveResourceGroupName == null)
                {
                    ArchiveResourceGroupName = ResourceGroupName;
                }

                _storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName);

                if (ConfigurationName == null)
                {
                    ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName);
                }

                if (ArchiveContainerName == null)
                {
                    ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName;
                }

                if (ArchiveStorageEndpointSuffix == null)
                {
                    ArchiveStorageEndpointSuffix =
                        DefaultProfile.DefaultContext.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
                }

                if (!(Regex.Match(Version, VersionRegexExpr).Success))
                {
                    this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscExtensionInvalidVersion);
                }
            }
        }
示例#59
0
        protected StorageServiceBase()
        {
            var credentials = new StorageCredentials("mkstorageazure", "YczBlDkuIWYIHvisw+OZ1kzo8dww9dOPRJyJ+Mt9gLw6y8BmBlys1gPGijKYtrxolYcterymd23THhjVy0T09g==");

            _storageAccount = new CloudStorageAccount(credentials, true);
        }
示例#60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudBlob"/> class using an absolute URI to the blob.
 /// </summary>
 /// <param name="blobAbsoluteUri">A <see cref="System.Uri"/> specifying the absolute URI to the blob.</param>
 /// <param name="credentials">A <see cref="StorageCredentials"/> object.</param>
 public CloudBlob(Uri blobAbsoluteUri, StorageCredentials credentials)
     : this(blobAbsoluteUri, null /* snapshotTime */, credentials)
 {
 }