Exemplo n.º 1
0
		/// <summary>
		/// Creates a blob container and sets its permission to public blobs, if the container does not already exist.
		/// </summary>
		/// <param name="container">The container to create.</param>
		/// <returns>
		/// A task whose result is <c>true</c> if the container did not exist before this method;
		///  <c>false</c> otherwise.
		/// </returns>
		public static async Task<bool> CreateContainerWithPublicBlobsIfNotExistAsync(this CloudBlobContainer container) {
			Requires.NotNull(container, "container");

			if (await container.CreateIfNotExistAsync()) {
				var permissions = new BlobContainerPermissions {
					PublicAccess = BlobContainerPublicAccessType.Blob,
				};
				await container.SetPermissionsAsync(permissions);
				return true;
			} else {
				return false;
			}
		}
Exemplo n.º 2
0
        // Read Blob message from container
        public async void listenBlob(string blobcontainername, string connectionString)
        {
            int maxloop = 1;

            for (int l = 0; l < maxloop; l++)
            {
                CloudStorageAccount storageAccount     = null;
                CloudBlobContainer  cloudBlobContainer = null;

                // Check whether the connection string can be parsed.
                if (CloudStorageAccount.TryParse(connectionString, out storageAccount))
                {
                    try
                    {
                        // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.
                        CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                        cloudBlobContainer = cloudBlobClient.GetContainerReference(blobcontainername);

                        // Set the permissions so the blobs are public.
                        BlobContainerPermissions permissions = new BlobContainerPermissions
                        {
                            PublicAccess = BlobContainerPublicAccessType.Blob
                        };
                        await cloudBlobContainer.SetPermissionsAsync(permissions);

                        // List the blobs in the container.
                        BlobContinuationToken blobContinuationToken = null;
                        do
                        {
                            var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);

                            // Get the value of the continuation token returned by the listing call.
                            blobContinuationToken = results.ContinuationToken;
                            foreach (IListBlobItem item in results.Results)
                            {
                                try
                                {
                                    var textFromAzureBlob = (new WebClient()).DownloadString(item.Uri);
                                    // Match device TFMini event
                                    MatchCollection match = Regex.Matches(textFromAzureBlob, @"""type""\:""([^""]*)"",""ident""\:""([^""]*)"",""enter""\:""([^""]*)""}", RegexOptions.IgnoreCase);

                                    for (int i = 0; i < match.Count; i++)
                                    {
                                        string       data   = "{" + match[i].Value;
                                        SensorDevice sensor = JsonConvert.DeserializeObject <SensorDevice>(data);
                                        // Send Sensor Object to Form Side
                                        OnNetClientReceived(this, new NetClientReceivedEventArgs(sensor.type, sensor));
                                        // Wait a little to dont lock Form GUI
                                        await Task.Delay(1000);

                                        // delete item
                                        ((ICloudBlob)item).Delete();
                                    }
                                }
                                catch (Exception ex) { string error = ex.Message; }
                            }
                        } while (blobContinuationToken != null); // Loop while the continuation token is not null.
                    }
                    catch (StorageException)
                    {
                        // Error returned from the service: {0}", ex.Message
                    }
                    finally
                    {
                        // After reading delete content
                        if (cloudBlobContainer != null)
                        {
                            // Not good delete the container itself
                            //await cloudBlobContainer.DeleteIfExistsAsync();
                            // Delete all items
                            // Parallel.ForEach(cloudBlobContainer.ListBlobs(useFlatBlobListing: true), x => ((CloudBlob)x).Delete());
                        }
                    }
                }
                //await Task.Delay(1000);
            }
        }
Exemplo n.º 3
0
        public static async Task BlobOperations()
        {
            string connectionString = Environment.GetEnvironmentVariable("storageconnectionstring");

            CloudStorageAccount storageAccount;

            if (CloudStorageAccount.TryParse(connectionString, out storageAccount))
            {
                try
                {
                    // Create blob container if not already created
                    Console.WriteLine("Creating blob container");
                    CloudBlobClient    blobClient    = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer blobContainer = blobClient.GetContainerReference("my-container");
                    await blobContainer.CreateIfNotExistsAsync(); //To-do handle exception Microsoft.WindowsAzure.Storage.StorageException

                    // Set access on the blob container
                    BlobContainerPermissions blobPermissions = new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    };
                    await blobContainer.SetPermissionsAsync(blobPermissions);

                    // Create a file for upload
                    Console.WriteLine("Creating temp file");
                    string currentDir = Directory.GetCurrentDirectory();
                    string fileName   = "hello.txt";
                    string file       = Path.Combine(currentDir, fileName);
                    await File.WriteAllTextAsync(file, "Hello, World!");

                    // Upload the file to the blob container
                    Console.WriteLine("Uploading file");
                    CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName);
                    await blockBlob.UploadFromFileAsync(file);

                    // List blobs in the container
                    Console.WriteLine("Listing blobs in container:");
                    BlobContinuationToken token = null;
                    do
                    {
                        var results = await blobContainer.ListBlobsSegmentedAsync(null, token);

                        token = results.ContinuationToken;
                        foreach (IListBlobItem item in results.Results)
                        {
                            Console.WriteLine("- " + item.Uri);
                        }
                    } while (token != null);

                    // Download the file from blob container
                    Console.WriteLine("Downloading file");
                    string downloadFile = file.Replace(".txt", "_downloaded.txt");
                    await blockBlob.DownloadToFileAsync(downloadFile, FileMode.Create);

                    // Delete blob container and files
                    Console.WriteLine("Blob container created, file uploaded, and copy downloaded.\n" +
                                      "Hit any key to delete resources.");
                    Console.ReadLine();
                    if (blobContainer != null)
                    {
                        await blobContainer.DeleteIfExistsAsync();
                    }
                    File.Delete(file);
                    File.Delete(downloadFile);
                    Console.WriteLine("Blob container and files have been deleted.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            }
            else
            {
                Console.WriteLine("The environment variable storageconnectionstring is not set."
                                  + "\nPlease set it and rerun this program.");
                Console.WriteLine("Hit any key to exit this program");
                Console.ReadLine();
            }
        }
 public ICancellableAsyncResult BeginSetPermissions(BlobContainerPermissions permissions, AccessCondition accessCondition,
                                                    BlobRequestOptions options, OperationContext operationContext,
                                                    AsyncCallback callback, object state)
 {
     throw new NotImplementedException();
 }
 public void SetPermissions(BlobContainerPermissions permissions, AccessCondition accessCondition = null,
                            BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     throw new NotImplementedException();
 }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string requestBody;
            //string storageConnectionString = Environment.GetEnvironmentVariable("storageconnectionstring");
            string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=inputsa;AccountKey=J3v5ZwzS34fR6pftCnptE7/PN3IFd0/hdZkR895F8N8iGKoV6MBUiZWQKTLmM1KwF8vTzArU7fo8DDW9uPIUnA==;EndpointSuffix=core.windows.net";
            CloudStorageAccount storageAccount;
            CloudBlobClient     cloudBlobClient;
            CloudBlobContainer  cloudBlobContainer;

            try
            {
                requestBody   = await new StreamReader(req.Body).ReadToEndAsync();
                worbixRequest = JsonConvert.DeserializeObject <WorbixRequest>(requestBody);

                if (worbixRequest.SiteId != null && worbixRequest.SpaceId != null && worbixRequest.ClientName != null && worbixRequest.ActorId != null
                    //&& worbixRequest.FileExtension!=null && worbixRequest.FileName !=null
                    && worbixRequest.DataSet != null)
                {
                    List <SqlParameter> sp = new List <SqlParameter>()
                    {
                        new SqlParameter()
                        {
                            ParameterName = "@SiteID", SqlDbType = System.Data.SqlDbType.NVarChar, Value = worbixRequest.SiteId
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@SpaceID", SqlDbType = System.Data.SqlDbType.NVarChar, Value = worbixRequest.SpaceId
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@ClienName", SqlDbType = System.Data.SqlDbType.NVarChar, Value = worbixRequest.ClientName
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@ActorID", SqlDbType = System.Data.SqlDbType.NVarChar, Value = worbixRequest.ActorId
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@DataSet", SqlDbType = System.Data.SqlDbType.NVarChar, Value = worbixRequest.DataSet
                        },
                        new SqlParameter()
                        {
                            ParameterName = "@FileUniqueID", SqlDbType = System.Data.SqlDbType.BigInt, Direction = System.Data.ParameterDirection.Output
                        }
                    };
                    var fileUniqueID = await RunStoredProcedure(sp);

                    if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
                    {
                        // If the connection string is valid, proceed with operations against Blob storage here.
                        cloudBlobClient    = storageAccount.CreateCloudBlobClient();
                        cloudBlobContainer = cloudBlobClient.GetContainerReference(worbixRequest.ClientName.ToLower());
                        await cloudBlobContainer.CreateIfNotExistsAsync();

                        //set permissions etc..get a token
                        BlobContainerPermissions permissions = new BlobContainerPermissions
                        {
                            PublicAccess = BlobContainerPublicAccessType.Blob
                        };

                        await cloudBlobContainer.SetPermissionsAsync(permissions);

                        return(new OkObjectResult(new WorbixResponse
                        {
                            FileUniqueID = fileUniqueID,
                            BlobContainerURL = cloudBlobContainer.Uri.ToString()
                        }));
                    }
                    return(new BadRequestObjectResult("Looks like storage account does not exist or you may not have required permissions. "));
                }
                return(new BadRequestObjectResult("Please pass siteId, spaceId and clientName parameters in the request body"));
            }
            catch (Exception e)
            {
                return(new BadRequestObjectResult("Request did not have valid body or generated an exception ->" + e.Message));
            }
        }
Exemplo n.º 7
0
        private async Task PrepareAsync()
        {
            _log.WriteLine("Making sure folder {0} exists.", _outputFolder);
            if (!Directory.Exists(_outputFolder))
            {
                Directory.CreateDirectory(_outputFolder);
            }

            // Create reindex file
            _log.WriteLine("Start preparing lightning reindex file...");

            var    latestCommit    = DateTime.MinValue;
            int    numberOfEntries = 0;
            string indexFile       = Path.Combine(_outputFolder, "index.txt");
            string storageCredentialArgumentsTemplate = "storageCredentialArguments";
            string optionalArgumentsTemplate          = "optionalArguments";

            using (var streamWriter = new StreamWriter(indexFile, false))
            {
                var httpMessageHandlerFactory = CommandHelpers.GetHttpMessageHandlerFactory(TelemetryService, _verbose);
                var collectorHttpClient       = new CollectorHttpClient(httpMessageHandlerFactory());
                var catalogIndexReader        = new CatalogIndexReader(new Uri(_catalogIndex), collectorHttpClient, TelemetryService);

                var catalogIndexEntries = await catalogIndexReader.GetEntries();

                foreach (var packageRegistrationGroup in catalogIndexEntries
                         .OrderBy(x => x.CommitTimeStamp)
                         .ThenBy(x => x.Id, StringComparer.OrdinalIgnoreCase)
                         .ThenBy(x => x.Version)
                         .GroupBy(x => x.Id, StringComparer.OrdinalIgnoreCase))
                {
                    streamWriter.WriteLine("Element@{0}. {1}", numberOfEntries++, packageRegistrationGroup.Key);

                    var latestCatalogPages = new Dictionary <string, Uri>();

                    foreach (CatalogIndexEntry catalogIndexEntry in packageRegistrationGroup)
                    {
                        string key = catalogIndexEntry.Version.ToNormalizedString();
                        if (latestCatalogPages.ContainsKey(key))
                        {
                            latestCatalogPages[key] = catalogIndexEntry.Uri;
                        }
                        else
                        {
                            latestCatalogPages.Add(key, catalogIndexEntry.Uri);
                        }

                        if (latestCommit < catalogIndexEntry.CommitTimeStamp)
                        {
                            latestCommit = catalogIndexEntry.CommitTimeStamp;
                        }
                    }

                    foreach (var latestCatalogPage in latestCatalogPages)
                    {
                        streamWriter.WriteLine("{0}", latestCatalogPage.Value);
                    }
                }
            }

            _log.WriteLine("Finished preparing lightning reindex file. Output file: {0}", indexFile);

            // Create the containers
            _log.WriteLine("Creating the containers...");
            var container  = GetAutofacContainer();
            var blobClient = container.Resolve <ICloudBlobClient>();
            var config     = container.Resolve <IOptionsSnapshot <Catalog2RegistrationConfiguration> >().Value;

            foreach (var name in new[] { config.LegacyStorageContainer, config.GzippedStorageContainer, config.SemVer2StorageContainer })
            {
                var reference   = blobClient.GetContainerReference(name);
                var permissions = new BlobContainerPermissions {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                };
                await reference.CreateIfNotExistAsync(permissions);
            }

            // Write cursor to storage
            _log.WriteLine("Start writing new cursor...");
            var storageFactory = container.ResolveKeyed <IStorageFactory>(DependencyInjectionExtensions.CursorBindingKey);
            var storage        = storageFactory.Create();
            var cursor         = new DurableCursor(storage.ResolveUri("cursor.json"), storage, latestCommit)
            {
                Value = latestCommit
            };

            await cursor.SaveAsync(CancellationToken.None);

            _log.WriteLine("Finished writing new cursor.");

            // Write command files
            _log.WriteLine("Start preparing lightning reindex command files...");

            string templateFileContents;

            using (var templateStreamReader = new StreamReader(_templateFile))
            {
                templateFileContents = await templateStreamReader.ReadToEndAsync();
            }

            int batchNumber    = 0;
            int batchSizeValue = int.Parse(_batchSize);

            for (int batchStart = 0; batchStart < numberOfEntries; batchStart += batchSizeValue)
            {
                var batchEnd = (batchStart + batchSizeValue - 1);
                if (batchEnd >= numberOfEntries)
                {
                    batchEnd = numberOfEntries - 1;
                }

                var cursorCommandFileName = "cursor" + batchNumber + ".cmd";
                var cursorTextFileName    = "cursor" + batchNumber + ".txt";

                using (var cursorCommandStreamWriter = new StreamWriter(Path.Combine(_outputFolder, cursorCommandFileName)))
                    using (var cursorTextStreamWriter = new StreamWriter(Path.Combine(_outputFolder, cursorTextFileName)))
                    {
                        var commandStreamContents = templateFileContents;

                        var replacements = _arguments
                                           .Concat(new[]
                        {
                            new KeyValuePair <string, string>("indexFile", indexFile),
                            new KeyValuePair <string, string>("cursorFile", cursorTextFileName)
                        });

                        foreach (var replacement in replacements)
                        {
                            commandStreamContents = commandStreamContents
                                                    .Replace($"[{replacement.Key}]", replacement.Value);
                        }

                        // Since we only need to set the storage key or the storage sas token, only one will be added to the template.
                        var storageCredentialArguments = new StringBuilder();
                        AddStorageCredentialArgument(storageCredentialArguments, Arguments.StorageSasValue, Arguments.StorageKeyValue);
                        AddStorageCredentialArgument(storageCredentialArguments, Arguments.CompressedStorageSasValue, Arguments.CompressedStorageKeyValue);
                        AddStorageCredentialArgument(storageCredentialArguments, Arguments.SemVer2StorageSasValue, Arguments.SemVer2StorageKeyValue);

                        commandStreamContents = commandStreamContents
                                                .Replace($"[{storageCredentialArgumentsTemplate}]", storageCredentialArguments.ToString());

                        //the not required arguments need to be added only if they were passed in
                        //they cannot be hardcoded in the template
                        var optionalArguments = new StringBuilder();
                        AppendArgument(optionalArguments, Arguments.FlatContainerName);
                        AppendArgument(optionalArguments, Arguments.StorageSuffix);
                        AppendArgument(optionalArguments, Arguments.Verbose);

                        commandStreamContents = commandStreamContents
                                                .Replace($"[{optionalArgumentsTemplate}]", optionalArguments.ToString());

                        await cursorCommandStreamWriter.WriteLineAsync(commandStreamContents);

                        await cursorTextStreamWriter.WriteLineAsync(batchStart + "," + batchEnd);
                    }

                batchNumber++;
            }

            _log.WriteLine("Finished preparing lightning reindex command files.");

            _log.WriteLine("You can now copy the {0} file and all cursor*.cmd, cursor*.txt", indexFile);
            _log.WriteLine("to multiple machines and run the cursor*.cmd files in parallel.");
        }
Exemplo n.º 8
0
        public static async Task <HttpResponseMessage> MVPRunPostItemToSpecifiedBlobContainer([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "PostMediaAssetToSpecifiedBlobContainer/{deviceId}/{videoTitle}")] HttpRequestMessage req, string deviceId, string videoTitle, TraceWriter log)
        {
            var fileAsBytes = await req.Content.ReadAsByteArrayAsync();

            var myUploadedFile = new UploadedFile
            {
                Title      = videoTitle,
                FileName   = $"{deviceId}_{DateTime.UtcNow.Ticks}.mp4",
                File       = fileAsBytes,
                UploadedAt = DateTime.UtcNow
            };

            ///////////////////////////////////
            ///// UPLOAD TO BLOB STORAGE
            //////////////////////////////////

            //THIS REQUIRES CONFIGURATION FILE
            //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            //CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Constants.BlobURLAndKey);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            string containerName = "mediaassetblobcontainer20170928";

            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

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

            //By default, the new container is private,
            //meaning that you must specify your storage access key to download blobs
            //from this container.If you want to make the files within the container available
            //to everyone, you can set the container to be public using the following code:

            var perm = new BlobContainerPermissions();

            perm.PublicAccess = BlobContainerPublicAccessType.Blob;
            container.SetPermissions(perm);

            //container.SetPermissions(new BlobContainerPermissions
            //{
            //    PublicAccess = BlobContainerPublicAccessType.Blob
            //});

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(myUploadedFile.FileName);

            //IN CASE YOU NEED TO SET THE MEDIA TYPE
            //https://stackoverflow.com/questions/24621664/uploading-blockblob-and-setting-contenttype

            try
            {
                ////////////////////////////////////////////////////////
                //UPLOAD FILE FROM BYTE ARRAY
                ////////////////////////////////////////////////////////

                blockBlob.UploadFromByteArray(myUploadedFile.File, 0, myUploadedFile.File.Length);

                //////////////////////////////////////////////////////
                /////////  SAVE TO COSMOS DB
                //////////////////////////////////////////////////////

                MediaAssetsWithMetaData uploadMediaAssetsWithMetaData = new MediaAssetsWithMetaData()
                {
                    id    = Guid.NewGuid().ToString(),
                    email = "*****@*****.**",
                    //mediaAssetUri = newLocator,
                    title      = myUploadedFile.Title,
                    fileName   = myUploadedFile.FileName,
                    uploadedAt = myUploadedFile.UploadedAt
                };

                await CosmosDB.CosmosDBService.PostMediaAssetAsync(uploadMediaAssetsWithMetaData);

                ////////////////////////////////////////////////////////
                //SEND HTTP RESPONSE MESSAGE
                ////////////////////////////////////////////////////////

                //HttpResponseMessage postFileInCreatedBlob2 = new HttpResponseMessage(HttpStatusCode.OK, "success");
                //httpRM.Content = new StringContent(jsonObject, System.Text.Encoding.UTF8, "application/json");

                return(req.CreateResponse <string>(HttpStatusCode.OK, "success"));
            }

            catch (Exception ex)
            {
                log.Error($"ERROR copying blobs to target output: {ex.Message}");

                ////////////////////////////////////////////////////////
                //SEND HTTP RESPONSE MESSAGE
                ////////////////////////////////////////////////////////

                HttpResponseMessage errorInCreatingBlob = new HttpResponseMessage(HttpStatusCode.BadRequest);
                var errorMessage = "Function did not upload to blob container.";
                errorInCreatingBlob.Content = new StringContent(errorMessage, System.Text.Encoding.UTF8, "application/json");
                return(errorInCreatingBlob);
            }
        }
Exemplo n.º 9
0
        private void SetPublicContainerPermissions(CloudBlobContainer container)
        {
            BlobContainerPermissions permissions = container.GetPermissionsAsync().Result;

            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
        }
        /// <summary>
        /// Reads the share access policies from a stream in XML.
        /// </summary>
        /// <param name="inputStream">The stream of XML policies.</param>
        /// <param name="permissions">The permissions object to which the policies are to be written.</param>
        public static Task ReadSharedAccessIdentifiersAsync(Stream inputStream, BlobContainerPermissions permissions, CancellationToken token)
        {
            CommonUtility.AssertNotNull("permissions", permissions);

            return(Response.ReadSharedAccessIdentifiersAsync(permissions.SharedAccessPolicies, new BlobAccessPolicyResponse(inputStream), token));
        }
Exemplo n.º 11
0
 /// <summary>
 /// Set container permissions
 /// </summary>
 /// <param name="container">A cloudblobcontainer object</param>
 /// <param name="permissions">The container's permission</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 public Task SetContainerPermissionsAsync(CloudBlobContainer container, BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cmdletCancellationToken)
 {
     return(Task.Factory.StartNew(() => this.SetContainerPermissions(container, permissions, accessCondition, requestOptions, operationContext)));
 }
 public Task SetPermissionsAsync(BlobContainerPermissions permissions)
 {
     throw new NotImplementedException();
 }
        public IHttpActionResult PostRequest(Request request)
        {
            request.RequestedDateTime = DateTime.Now;

            var credentials = SdkContext.AzureCredentialsFactory
                              .FromServicePrincipal("c99526ff-46a7-4c14-a3dd-c007179c3f1f",
                                                    "fuKHqKJOJfB4ZiU2AaNMGx3qyMzlsaviKZ3b2L73z1s=",
                                                    "54c2e137-49f4-4774-afbe-172aae73f061",
                                                    AzureEnvironment.AzureGlobalCloud);

            var azure = Microsoft.Azure.Management.Fluent.Azure
                        .Configure()
                        .Authenticate(credentials)
                        .WithSubscription("dab0b14c-927c-4d0a-99b6-2ae522a7f341");

            var groupName = request.UserName + "RG";
            var vmName    = request.UserName + "VM";
            var location  = Region.USWest;

            var resourceGroup = azure.ResourceGroups.Define(groupName)
                                .WithRegion(location)
                                .Create();

            if (request.VMType.Equals(".NET SDK"))
            {
                var availabilitySet = azure.AvailabilitySets.Define(request.UserName + "AVSet")
                                      .WithRegion(location)
                                      .WithExistingResourceGroup(groupName)
                                      .WithSku(AvailabilitySetSkuTypes.Managed)
                                      .Create();

                var publicIPAddress = azure.PublicIPAddresses.Define(request.UserName + "PublicIP")
                                      .WithRegion(location)
                                      .WithExistingResourceGroup(groupName)
                                      .WithDynamicIP()
                                      .Create();

                var network = azure.Networks.Define(request.UserName + "VNet")
                              .WithRegion(location)
                              .WithExistingResourceGroup(groupName)
                              .WithAddressSpace("10.0.0.0/16")
                              .WithSubnet("mySubnet", "10.0.0.0/24")
                              .Create();

                var networkInterface = azure.NetworkInterfaces.Define(request.UserName + "NIC")
                                       .WithRegion(location)
                                       .WithExistingResourceGroup(groupName)
                                       .WithExistingPrimaryNetwork(network)
                                       .WithSubnet("mySubnet")
                                       .WithPrimaryPrivateIPAddressDynamic()
                                       .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                       .Create();

                azure.VirtualMachines.Define(vmName)
                .WithRegion(location)
                .WithExistingResourceGroup(groupName)
                .WithExistingPrimaryNetworkInterface(networkInterface)
                .WithLatestWindowsImage("MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
                .WithAdminUsername("AzureUser")
                .WithAdminPassword("Vijay@123")
                .WithComputerName(vmName)
                .WithExistingAvailabilitySet(availabilitySet)
                .WithSize(VirtualMachineSizeTypes.StandardDS1)
                .Create();

                var vm = azure.VirtualMachines.GetByResourceGroup(groupName, vmName);

                request.VMSize = vm.Size.ToString();
                request.IP     = vm.GetPrimaryPublicIPAddress().IPAddress;
            }

            else
            {
                string storageAccountName = SdkContext.RandomResourceName("st", 10);

                Console.WriteLine("Creating storage account...");
                var storage = azure.StorageAccounts.Define(storageAccountName)
                              .WithRegion(Region.USWest)
                              .WithExistingResourceGroup(resourceGroup)
                              .Create();

                var    storageKeys             = storage.GetKeys();
                string storageConnectionString = "DefaultEndpointsProtocol=https;"
                                                 + "AccountName=" + storage.Name
                                                 + ";AccountKey=" + storageKeys[0].Value
                                                 + ";EndpointSuffix=core.windows.net";

                var account       = CloudStorageAccount.Parse(storageConnectionString);
                var serviceClient = account.CreateCloudBlobClient();

                var container = serviceClient.GetContainerReference("templates");
                container.CreateIfNotExistsAsync().Wait();
                var containerPermissions = new BlobContainerPermissions()
                {
                    PublicAccess = BlobContainerPublicAccessType.Container
                };
                container.SetPermissionsAsync(containerPermissions).Wait();

                var templateblob = container.GetBlockBlobReference("CreateVMTemplate.json");
                templateblob.UploadFromFileAsync("F:\\Vijay\\ILP-003\\ILP-003\\CreateVMTemplate.json");

                var paramblob = container.GetBlockBlobReference("Parameters.json");
                paramblob.UploadFromFileAsync("F:\\Vijay\\ILP-003\\ILP-003\\Parameters.json");

                var templatePath = "https://" + storageAccountName + ".blob.core.windows.net/templates/CreateVMTemplate.json";
                var paramPath    = "https://" + storageAccountName + ".blob.core.windows.net/templates/Parameters.json";
                var deployment   = azure.Deployments.Define("myDeployment")
                                   .WithExistingResourceGroup(groupName)
                                   .WithTemplateLink(templatePath, "1.0.0.0")
                                   .WithParametersLink(paramPath, "1.0.0.0")
                                   .WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
                                   .Create();

                var vm = azure.VirtualMachines.GetByResourceGroup(groupName, "myVM");
                request.VMSize = vm.Size.ToString();
                request.IP     = vm.GetPrimaryPublicIPAddress().IPAddress;
            }

            db.requests.Add(request);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = request.Id }, request));
        }
Exemplo n.º 14
0
 public static void ReadSharedAccessIdentifiers(Stream inputStream, BlobContainerPermissions permissions)
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 15
0
        public async Task <IActionResult> UploadFileNow(ICollection <IFormFile> files)
        {
            var blogId = Convert.ToInt32(Request.Form["id"]);

            // get your storage accounts connection string
            var storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=cst8359;AccountKey=ecMPpNU6vimZKMDTJG4seALrY7Kq7UJYjgl0/yLanXn857C8xtUJ2sF4ciB6wy9gg+e/YeYbRTaly2DVOxWhXQ==");

            // create an instance of the blob client
            var blobClient = storageAccount.CreateCloudBlobClient();

            // create a container to hold your blob (binary large object.. or something like that)
            // naming conventions for the curious https://msdn.microsoft.com/en-us/library/dd135715.aspx
            var container = blobClient.GetContainerReference("khasmaisphotostorage");
            await container.CreateIfNotExistsAsync();

            // set the permissions of the container to 'blob' to make them public
            var permissions = new BlobContainerPermissions();

            permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
            await container.SetPermissionsAsync(permissions);

            // for each file that may have been sent to the server from the client
            foreach (var file in files)
            {
                try
                {
                    // create the blob to hold the data
                    var blockBlob = container.GetBlockBlobReference(file.FileName);
                    if (await blockBlob.ExistsAsync())
                    {
                        await blockBlob.DeleteAsync();
                    }

                    using (var memoryStream = new MemoryStream())
                    {
                        // copy the file data into memory
                        await file.CopyToAsync(memoryStream);

                        // navigate back to the beginning of the memory stream
                        memoryStream.Position = 0;

                        // send the file to the cloud
                        await blockBlob.UploadFromStreamAsync(memoryStream);
                    }

                    // add the photo to the database if it uploaded successfully

                    var photo = new Photo();

                    photo.BlogPostId = blogId;
                    photo.Url        = blockBlob.Uri.AbsoluteUri;
                    photo.Filename   = file.FileName;

                    _blogContext.Photos.Add(photo);
                    _blogContext.SaveChanges();
                }
                catch
                {
                }
            }

            return(RedirectToAction("EditBlogPost", new { id = blogId }));
        }
Exemplo n.º 16
0
        private static async Task ProcessAsync()
        {
            var storageConnectionString = Environment.GetEnvironmentVariable("storageconnectionstring");

            CloudStorageAccount storageAccount = null;

            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                try {
                    var cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    var cloudBlobContainer = cloudBlobClient.GetContainerReference("mycontainer" + Guid.NewGuid().ToString());
                    await cloudBlobContainer.CreateAsync();

                    var permissions = new BlobContainerPermissions {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    };
                    await cloudBlobContainer.SetPermissionsAsync(permissions);

                    var    localPath     = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    string localFileName = "QuickStart_" + Guid.NewGuid().ToString() + ".txt";
                    sourceFile = Path.Combine(localPath, localFileName);
                    File.WriteAllText(sourceFile, "Hello, World!");

                    var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(localFileName);
                    await cloudBlockBlob.UploadFromFileAsync(sourceFile);

                    // List the blobs in the container.
                    Console.WriteLine("Listing blobs in container.");
                    BlobContinuationToken blobContinuationToken = null;
                    do
                    {
                        var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);

                        blobContinuationToken = results.ContinuationToken;
                        foreach (IListBlobItem item in results.Results)
                        {
                            Console.WriteLine(item.Uri);
                        }
                    } while (blobContinuationToken != null); // Loop while the continuation token is not null.

                    destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");
                    await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create);
                }
                catch (StorageException ex)
                {
                    Console.WriteLine("Error returned from the service: {0}", ex.Message);
                }
                finally
                {
                    Console.WriteLine("Press any key to delete the sample files and example container.");
                    Console.ReadLine();
                    // Clean up resources. This includes the container and the two temp files.
                    Console.WriteLine("Deleting the container and any blobs it contains");
                    if (cloudBlobContainer != null)
                    {
                        await cloudBlobContainer.DeleteIfExistsAsync();
                    }
                    Console.WriteLine("Deleting the local source file and local downloaded files");
                    Console.WriteLine();
                    File.Delete(sourceFile);
                    File.Delete(destinationFile);
                }
            }
            else
            {
                Console.WriteLine(
                    "A connection string has not been defined in the system environment variables. " +
                    "Add a environment variable named 'storageconnectionstring' with your storage " +
                    "connection string as a value.");
            }
        }
 public Task CreateIfNotExistAsync(BlobContainerPermissions permissions)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Reads the share access policies from a stream in XML.
        /// </summary>
        /// <param name="inputStream">The stream of XML policies.</param>
        /// <param name="permissions">The permissions object to which the policies are to be written.</param>
        public static void ReadSharedAccessIdentifiers(Stream inputStream, BlobContainerPermissions permissions)
        {
            CommonUtility.AssertNotNull("permissions", permissions);

            Response.ReadSharedAccessIdentifiers(permissions.SharedAccessPolicies, new BlobAccessPolicyResponse(inputStream));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Puts the specified object onto the cloud storage provider.
        /// </summary>
        /// <param name="o">The object to store.</param>
        public void Put(AzureCloudFile o)
        {
            if (o.Data == null)
            {
                throw new ArgumentNullException("o", "AzureCloudFile cannot be null.");
            }

            if (o.Uri == null)
            {
                throw new ArgumentException("Parameter 'Uri' of argument 'o' cannot be null.");
            }

            string path = o.Uri.ToString();

            if (path.StartsWith(@"/"))
            {
                path = path.Remove(0, 1);
            }

            if (path.StartsWith(@"\\"))
            {
                path = path.Remove(0, 1);
            }

            if (path.StartsWith(@"\"))
            {
                path = path.Remove(0, 1);
            }

            // Remove double back slashes from anywhere in the path
            path = path.Replace(@"\\", @"\");

            CloudBlobContainer container = _blobClient.GetContainerReference(ContainerName);

            container.CreateIfNotExist();

            // Set permissions on the container
            BlobContainerPermissions perms = container.GetPermissions();

            if (perms.PublicAccess != BlobContainerPublicAccessType.Container)
            {
                perms.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(perms);
            }


            // Create a reference for the filename
            String uniqueName = path;

            blob = container.GetBlobReference(uniqueName);

            // Create a new AsyncCallback instance
            AsyncCallback callback = PutOperationCompleteCallback;



            blob.BeginUploadFromStream(new MemoryStream(o.Data), callback, o.Uri);


            // Uncomment for synchronous upload
            // blob.UploadFromStream(new System.IO.MemoryStream(o.Data));
        }
Exemplo n.º 20
0
        public static async Task RunAsync()
        {
            var storageAccount = CloudStorageAccount
                                 .Parse(_connectionString);
            var cloudBlobClient = storageAccount
                                  .CreateCloudBlobClient();

            var cloudBlobContainer = cloudBlobClient
                                     .GetContainerReference("mycontainer");
            await cloudBlobContainer.CreateAsync();

            var permissions = new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            };
            await cloudBlobContainer.SetPermissionsAsync(permissions);

            var localFileName = "Blob.txt";

            File.WriteAllText(localFileName, "Hello, World!");

            var cloudBlockBlob = cloudBlobContainer
                                 .GetBlockBlobReference(localFileName);
            await cloudBlockBlob.UploadFromFileAsync(localFileName);

            // List the blobs in the container.
            Console.WriteLine("Listing blobs in container.");
            BlobContinuationToken blobContinuationToken = null;

            do
            {
                var results = await cloudBlobContainer
                              .ListBlobsSegmentedAsync(null,
                                                       blobContinuationToken);

                blobContinuationToken = results.ContinuationToken;
                foreach (var item in results.Results)
                {
                    Console.WriteLine(item.Uri);
                }
            } while (blobContinuationToken != null);

            var destinationFile = localFileName.Replace(".txt", "_DOWNLOADED.txt");
            await cloudBlockBlob.DownloadToFileAsync(
                destinationFile, FileMode.Create);

            var leaseId = Guid.NewGuid().ToString();

            File.WriteAllText(localFileName, "New Content");

            cloudBlockBlob.AcquireLease(
                TimeSpan.FromSeconds(30),
                leaseId);

            try
            {
                await cloudBlockBlob.UploadFromFileAsync(localFileName);
            }
            catch (StorageException ex)
            {
                System.Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    System.Console.WriteLine(ex.InnerException.Message);
                }
            }

            await Task.Delay(TimeSpan.FromSeconds(5));

            await cloudBlockBlob.UploadFromFileAsync(localFileName);

            // or release it
            await cloudBlockBlob.ReleaseLeaseAsync(
                new AccessCondition()
            {
                LeaseId = leaseId
            });

            await cloudBlobContainer.DeleteIfExistsAsync();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonbuttonUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BackgroundWorker backgroundWorker = new BackgroundWorker();

                Exception exceptionError = null;

                string account       = textBoxStorateAccount.Text.Trim();
                string key           = passwordBoxSharedKey.Password.Trim();
                string containerName = textBoxContainerName.Text.Trim();

                backgroundWorker.DoWork += delegate(object s, DoWorkEventArgs args)
                {
                    try
                    {
                        StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(account, key);

                        CloudBlobClient client = new CloudBlobClient("http://" + account + ".blob.core.windows.net", credentials);

                        CloudBlobContainer container;
                        CloudBlob          blob;

                        container = new CloudBlobContainer(containerName, client);
                        BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
                        containerPermissions.PublicAccess = BlobContainerPublicAccessType.Container;
                        container.CreateIfNotExist();
                        container.SetPermissions(containerPermissions);

                        string directoryName = new FileInfo(fovFilename).Directory.FullName;

                        blob = new CloudBlob(containerName + "/" + manifestInfo.Name + ".ism/Manifest", client);
                        blob.DeleteIfExists();
                        blob.Properties.ContentType = "text/xml";
                        blob.UploadFile(manifestInfo.Filename);

                        foreach (string line in File.ReadAllLines(fovFilename))
                        {
                            string[] arr = line.Split(',');

                            string mediatype = arr[0].Split('=')[1];
                            string bitrate   = arr[1].Split('=')[1];
                            string starttime = arr[2].Split('=')[1];
                            string file      = arr[3].Split('=')[1];
                            string offset    = arr[4].Split('=')[1];
                            string size      = arr[5].Split('=')[1];

                            string path = string.Format("{0}/{1}.ism/QualityLevels({2})/Fragments({3}={4})", containerName, manifestInfo.Name, bitrate, mediatype, starttime);

                            FileStream stream = File.OpenRead(Path.Combine(directoryName, file));

                            byte[] buffer = new byte[int.Parse(size)];
                            stream.Position = int.Parse(offset);
                            stream.Read(buffer, 0, buffer.Length);

                            stream.Close();

                            blob = new CloudBlob(path, client);
                            blob.DeleteIfExists();
                            blob.Properties.ContentType = "video/mp4";
                            blob.UploadByteArray(buffer);
                        }
                    }
                    catch (Exception ex)
                    {
                        exceptionError = ex;
                    }
                };

                ProgressWindow progressWindow = new ProgressWindow();

                progressWindow.Owner  = this;
                progressWindow.Worker = backgroundWorker;

                progressWindow.ShowDialog();

                if (exceptionError == null)
                {
                    MessageBox.Show("Video uploaded to Azure Storage account.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    throw exceptionError;
                }
            }
            catch (Exception ex)
            {
                ErrorWindow errorWin = new ErrorWindow("Error uploading to azure.", ex);
                errorWin.Owner = this;
                errorWin.ShowDialog();
            }
        }
Exemplo n.º 22
0
        private static async Task ProcessAsync()
        {
            CloudStorageAccount storageAccount     = null;
            CloudBlobContainer  cloudBlobContainer = null;
            string sourceFile      = null;
            string destinationFile = null;

            // Retrieve the connection string for use with the application. The storage connection string is stored
            // in an environment variable on the machine running the application called storageconnectionstring.
            // If the environment variable is created after the application is launched in a console or with Visual
            // Studio, the shell needs to be closed and reloaded to take the environment variable into account.
            string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=srihari;AccountKey=5A7TI1XY/QKO6YC8tMxmrPdhwL3FvT3kbImU9f67a1BWMFRs7W3WhM7t3/LWIg60k1aLBkV7fDSxk7C/zUpOXA==;EndpointSuffix=core.windows.net";

            // Check whether the connection string can be parsed.
            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                try
                {
                    // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.
                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    // Create a container called 'quickstartblobs' and append a GUID value to it to make the name unique.
                    cloudBlobContainer = cloudBlobClient.GetContainerReference("neututorialblob");
                    await cloudBlobContainer.CreateAsync();

                    Console.WriteLine("Created container '{0}'", cloudBlobContainer.Name);
                    Console.WriteLine();

                    // Set the permissions so the blobs are public.
                    BlobContainerPermissions permissions = new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    };
                    await cloudBlobContainer.SetPermissionsAsync(permissions);

                    // Create a file in your local MyDocuments folder to upload to a blob.
                    string localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    //string localFileName = "QuickStart_" + Guid.NewGuid().ToString() + ".txt";
                    //sourceFile = Path.Combine(localPath, localFileName);
                    //Write text to the file.
                    //File.WriteAllText(sourceFile, "Hello, World!");

                    string localFileName = "NeuTutorialDocument.txt";
                    sourceFile = Path.Combine(localPath, localFileName);
                    Console.WriteLine("Temp file = {0}", sourceFile);
                    Console.WriteLine("Uploading to Blob storage as blob '{0}'", localFileName);
                    Console.WriteLine();

                    // Get a reference to the blob address, then upload the file to the blob.
                    // Use the value of localFileName for the blob name.
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(localFileName);
                    await cloudBlockBlob.UploadFromFileAsync(sourceFile);

                    // List the blobs in the container.
                    Console.WriteLine("Listing blobs in container.");
                    BlobContinuationToken blobContinuationToken = null;
                    do
                    {
                        var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);

                        // Get the value of the continuation token returned by the listing call.
                        blobContinuationToken = results.ContinuationToken;
                        foreach (IListBlobItem item in results.Results)
                        {
                            Console.WriteLine(item.Uri);
                        }
                    } while (blobContinuationToken != null); // Loop while the continuation token is not null.
                    Console.WriteLine();

                    // Download the blob to a local file, using the reference created earlier.
                    // Append the string "_DOWNLOADED" before the .txt extension so that you can see both files in MyDocuments.
                    destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");
                    Console.WriteLine("Downloading blob to {0}", destinationFile);
                    Console.WriteLine();
                    await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create);
                }
                catch (StorageException ex)
                {
                    Console.WriteLine("Error returned from the service: {0}", ex.Message);
                }
                //finally
                //{
                //    Console.WriteLine("Press any key to delete the sample files and example container.");
                //    Console.ReadLine();
                //    // Clean up resources. This includes the container and the two temp files.
                //    Console.WriteLine("Deleting the container and any blobs it contains");
                //    if (cloudBlobContainer != null)
                //    {
                //        await cloudBlobContainer.DeleteIfExistsAsync();
                //    }
                //    Console.WriteLine("Deleting the local source file and local downloaded files");
                //    Console.WriteLine();
                //    File.Delete(sourceFile);
                //    File.Delete(destinationFile);
                //}
            }
            else
            {
                Console.WriteLine(
                    "A connection string has not been defined in the system environment variables. " +
                    "Add a environment variable named 'storageconnectionstring' with your storage " +
                    "connection string as a value.");
            }
        }
Exemplo n.º 23
0
        private async void FaceQuery(StorageFile file)
        {
            CloudBlockBlob blob         = null;
            string         blobFileName = null;

            if (null != file)
            {
                txtResponse.Text = "";
                progressRingMainPage.IsActive = true;
                BitmapImage         bitmapImage = new BitmapImage();
                IRandomAccessStream fileStream  = await file.OpenAsync(FileAccessMode.Read);

                bitmapImage.SetSource(fileStream);
                CapturedPhoto.Source = bitmapImage;
                CapturedPhoto.Tag    = file.Path;

                blobFileName = System.Guid.NewGuid() + "." + file.Name.Split('.').Last <string>();

                await HttpHandler.tempContainer.CreateIfNotExistsAsync();

                BlobContainerPermissions permissions = new BlobContainerPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                await HttpHandler.tempContainer.SetPermissionsAsync(permissions);

                blob = HttpHandler.tempContainer.GetBlockBlobReference(blobFileName);
                await blob.DeleteIfExistsAsync();

                await blob.UploadFromFileAsync(file);

                string              uri        = "https://api.projectoxford.ai/face/v1.0/detect?returnFaceId=true";
                string              jsonString = "{\"url\":\"" + HttpHandler.storagePath + "visitors/" + blobFileName + "\"}";
                HttpContent         content    = new StringContent(jsonString, Encoding.UTF8, "application/json");
                HttpResponseMessage response   = await HttpHandler.client.PostAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();

                    if (null == globals.gPersonGroupList)
                    {
                        globals.gPersonGroupList = await PersonGroupCmds.ListPersonGroups();
                    }

                    List <string> names = await VisitorCmds.CheckVisitorFace(responseBody, globals.gPersonGroupList);

                    if (0 == names.Count)
                    {
                        txtResponse.Text = "Sorry, I don't know.";
                    }
                    else
                    {
                        txtResponse.Text = string.Join(", ", names.ToArray());
                    }
                }
                else
                {
                    string responseBody = await response.Content.ReadAsStringAsync();

                    globals.ShowJsonErrorPopup(responseBody);
                }

                await blob.DeleteAsync();

                progressRingMainPage.IsActive = false;
            }
        }
Exemplo n.º 24
0
        public static ActionResult CreateContainer(string containerName, string accountName, string accountKey, bool useHttps)
        {
            ActionResult       actionResult = new ActionResult();
            StorageCredentials sc;

            try
            {
                sc = new StorageCredentials(accountName, accountKey);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                actionResult.AddError("AuthenticationFailure", Localization.GetString("AuthenticationFailure.ErrorMessage", Components.Constants.LocalResourceFile));
                return(actionResult);
            }

            CloudStorageAccount csa        = new CloudStorageAccount(sc, useHttps);
            CloudBlobClient     blobClient = csa.CreateCloudBlobClient();
            CloudBlobContainer  container  = blobClient.GetContainerReference(containerName);

            try
            {
                if (container.CreateIfNotExists())
                {
                    BlobContainerPermissions permissions = container.GetPermissions();
                    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                    container.SetPermissions(permissions);
                }
                actionResult.IsSuccess = true;
                return(actionResult);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.ExtendedErrorInformation != null)
                {
                    switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode)
                    {
                    case "AccountNotFound":
                        actionResult.AddError("AccountNotFound", Localization.GetString("AccountNotFound.ErrorMessage", Components.Constants.LocalResourceFile));
                        break;

                    case "AuthenticationFailure":
                        actionResult.AddError("AuthenticationFailure", Localization.GetString("AuthenticationFailure.ErrorMessage", Components.Constants.LocalResourceFile));
                        break;

                    case "AccessDenied":
                        actionResult.AddError("AccessDenied", Localization.GetString("AccessDenied.ErrorMessage", Components.Constants.LocalResourceFile));
                        break;

                    case "ContainerAlreadyExists":
                        actionResult.IsSuccess = true;
                        return(actionResult);

                    default:
                        DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                        actionResult.AddError("NewContainer", Localization.GetString("NewContainer.ErrorMessage", Components.Constants.LocalResourceFile));
                        break;
                    }
                }
                else
                {
                    actionResult.AddError("InternalError", ex.Message);
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                actionResult.AddError("NewContainer", Localization.GetString("NewContainer.ErrorMessage", Components.Constants.LocalResourceFile));
            }

            return(actionResult);
        }
Exemplo n.º 25
0
 public ICancellableAsyncResult BeginSetPermissions(BlobContainerPermissions permissions, AsyncCallback callback, object state)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 26
0
 public Task SetPermissionsAsync(BlobContainerPermissions permissions)
 {
     return(Task.Factory.FromAsync(
                _blobContainer.BeginSetPermissions(permissions, null, null),
                _blobContainer.EndSetPermissions));
 }
 /// <summary>
 /// Return a task that asynchronously set the container permission
 /// </summary>
 /// <param name="container">CloudBlobContainer object</param>
 /// <param name="permissions">Container permission</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="requestOptions">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">cancellation token</param>
 /// <returns>Return a task that asynchronously set the container permission</returns>
 public Task SetContainerPermissionsAsync(CloudBlobContainer container, BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions requestOptions, XSCL.OperationContext operationContext, CancellationToken cancellationToken)
 {
     return(container.SetPermissionsAsync(permissions, accessCondition, requestOptions, operationContext, cancellationToken));
 }
Exemplo n.º 28
0
        /* --------------------------------------------------------------------------------------- */


        /* --------------------------------------------------------------------------------------- */
        // Subirá solo los modificados.
        private static async Task ProcessAsync(string fileOld, string fileNew)
        {
            // Variable de Entorno para la conexión con el servicio
            Console.WriteLine("Obteniendo Variable de Entorno...");
            string storageConnectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");

            Console.WriteLine(" [OK]\n\n");
            Console.WriteLine("Realizando conexión...");
            // Check whether the connection string can be parsed.
            CloudStorageAccount storageAccount;

            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                // If the connection string is valid, proceed with operations against Blob
                // storage here.
                // ADD OTHER OPERATIONS HERE
                // Create the CloudBlobClient that represents the
                // Blob storage endpoint for the storage account.
                CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                // Create a container called 'quickstartblobs' and
                // append a GUID value to it to make the name unique.
                CloudBlobContainer cloudBlobContainer =
                    cloudBlobClient.GetContainerReference(contenedorNombre); // Nombre del contenedor
                // Guid.NewGuid().ToString());
                // await cloudBlobContainer.CreateAsync();

                // SI NO EXISTE EL CONTENEDOR LO CREA, SI EXISTE MODIFICA SU CONTENIDO
                await cloudBlobContainer.CreateIfNotExistsAsync();

                // Set the permissions so the blobs are public.
                BlobContainerPermissions permissions = new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                };
                await cloudBlobContainer.SetPermissionsAsync(permissions);

                // Create a file in your local MyDocuments folder to upload to a blob.

                /*
                 * string localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                 * string localFileName = "QuickStart_" + Guid.NewGuid().ToString() + ".txt";
                 * string sourceFile = Path.Combine(localPath, localFileName);
                 */
                // Write text to the file.
                // File.WriteAllText(sourceFile, "Hello, World!");

                // AQUI SE CAMBIA EL DIRECTORIO DONDE SE ENCUENTRA LA CARPETA QUE SE QUIERE SUBIR SU CONTENIDO Y EL TIPO DE ARCHIVO.
                // string[] files = Directory.GetFiles(ruta, extension);
                if (fileOld.Equals(fileNew))
                {
                    string sourceFile = Path.Combine(ruta, fileNew);

                    Console.WriteLine("Subiendo a Blob storage como blob '{0}'...", fileNew);
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileNew);
                    await cloudBlockBlob.UploadFromFileAsync(sourceFile);

                    Console.WriteLine("[OK]\n");
                }
                else
                {
                    string sourceFile = Path.Combine(ruta, fileNew);

                    Console.WriteLine("sustituyendo " + fileOld + " como " + fileNew + " a Blob storage como blob...");
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileOld);
                    await cloudBlockBlob.DeleteIfExistsAsync();

                    cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileNew);
                    await cloudBlockBlob.UploadFromFileAsync(sourceFile);

                    Console.WriteLine("[OK]");

                    textoInicio();
                }
            }
            else
            {
                Console.WriteLine("[ERROR]\n\n");
                // Otherwise, let the user know that they need to define the environment variable.
                Console.WriteLine(
                    "La conexión falló.\n " +
                    "Puede ser por las siguiente opciones:\n" +
                    "  - Variable de Entorno no definida. \n" +
                    "  - Variable de Entorno incorrecta o caduca. \n\n" +
                    "En caso de la primera opción, Añada una Variable de Entorno de Sistema llamada 'STORAGE_CONNECTION_STRING'\n" +
                    " y como valor añada la key Connection String. Ejemplo: 'DefaultEndpointsProtocol=https;AccountName=triplealpha;AccountKey=fQsntF2...'\n\n");
                Console.WriteLine("Pulse cualquier tecla para salir de la aplicación.");
                Console.ReadLine();
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Set container permissions
 /// </summary>
 /// <param name="container">A cloudblobcontainer object</param>
 /// <param name="permissions">The container's permission</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="options">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 public void SetContainerPermissions(CloudBlobContainer container, BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     container.SetPermissions(permissions, accessCondition, options, operationContext);
 }
Exemplo n.º 30
0
        /* --------------------------------------------------------------------------------------- */
        // Subirá todos los archivos de la carpeta.
        private static async Task ProcessAsync()
        {
            // Variable de Entorno para la conexión con el servicio
            Console.WriteLine("Obteniendo Variable de Entorno...");
            string storageConnectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");

            Console.WriteLine(" [OK]\n\n");
            Console.WriteLine("Realizando conexión...");
            // Check whether the connection string can be parsed.
            CloudStorageAccount storageAccount;

            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                Console.WriteLine("[OK]\n\n");
                // If the connection string is valid, proceed with operations against Blob
                // storage here.

                // Create the CloudBlobClient that represents the
                // Blob storage endpoint for the storage account.
                CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                // Create a container called 'quickstartblobs' and
                // append a GUID value to it to make the name unique.
                CloudBlobContainer cloudBlobContainer =
                    cloudBlobClient.GetContainerReference(contenedorNombre); // Nombre del contenedor

                // SI NO EXISTE EL CONTENEDOR LO CREA, SI EXISTE MODIFICA SU CONTENIDO
                await cloudBlobContainer.CreateIfNotExistsAsync();

                // Set the permissions so the blobs are public.
                BlobContainerPermissions permissions = new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                };
                await cloudBlobContainer.SetPermissionsAsync(permissions);

                // AQUI SE CAMBIA EL DIRECTORIO DONDE SE ENCUENTRA LA CARPETA QUE SE QUIERE SUBIR SU CONTENIDO Y EL TIPO DE ARCHIVO.
                string[] files = Directory.GetFiles(ruta, extension);
                Console.WriteLine("Subiendo archivos de " + ruta + "\n\n");
                foreach (string filePath in files)
                {
                    string fileName = Path.GetFileName(filePath);
                    Console.WriteLine("Archivo = {0}", filePath);
                    Console.WriteLine();
                    Console.WriteLine("Subiendo a Blob storage como blob '{0}'...", fileName);
                    Console.WriteLine();
                    // Get a reference to the blob address, then upload the file to the blob.
                    // Use the value of localFileName for the blob name.
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
                    await cloudBlockBlob.UploadFromFileAsync(filePath);
                }

                textoInicio();
            }
            else
            {
                Console.WriteLine("[ERROR]\n\n");
                // Otherwise, let the user know that they need to define the environment variable.
                Console.WriteLine(
                    "La conexión falló.\n " +
                    "Puede ser por las siguiente opciones:\n" +
                    "  - Variable de Entorno no definida. \n" +
                    "  - Variable de Entorno incorrecta o caduca. \n\n" +
                    "En caso de la primera opción, Añada una Variable de Entorno de Sistema llamada 'STORAGE_CONNECTION_STRING'\n" +
                    " y como valor añada la key Connection String. Ejemplo: 'DefaultEndpointsProtocol=https;AccountName=triplealpha;AccountKey=fQsntF2...'\n\n");
                Console.WriteLine("Pulse cualquier tecla para salir de la aplicación.");
                Console.ReadLine();
            }
        }
        /// <summary>
        /// Reads the share access policies from a stream in XML.
        /// </summary>
        /// <param name="inputStream">The stream of XML policies.</param>
        /// <param name="permissions">The permissions object to which the policies are to be written.</param>
        public static void ReadSharedAccessIdentifiers(Stream inputStream, BlobContainerPermissions permissions)
        {
            CommonUtility.AssertNotNull("permissions", permissions);

            Response.ReadSharedAccessIdentifiers(permissions.SharedAccessPolicies, new BlobAccessPolicyResponse(inputStream));
        }
Exemplo n.º 32
0
        public static async Task ProcessAsync(Message encodedMessage)
        {
            CloudStorageAccount storageAccount     = null;
            CloudBlobContainer  cloudBlobContainer = null;
            string sourceFile      = null;
            string destinationFile = null;

            // Retrieve the connection string for use with the application. The storage connection string is stored
            // in an environment variable on the machine running the application called storageconnectionstring.
            // If the environment variable is created after the application is launched in a console or with Visual
            // Studio, the shell needs to be closed and reloaded to take the environment variable into account.
            //string storageConnectionString = Environment.GetEnvironmentVariable("storageconnectionstring");
            //setx storageconnectionstring "<yourconnectionstring>"
            string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=iothubstorageaccount01;AccountKey=4XCCWygYeGJDv0bb2QruYb2SGBS8/sJYEGJEsJ8iQ2CZ8L65+gPfd5vMcqgFjOrzIPWjr/tbPFFNBV6cn0oQeg==;EndpointSuffix=core.windows.net";

            // Check whether the connection string can be parsed.
            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                try
                {
                    // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.
                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    var fileContainer = cloudBlobClient.GetContainerReference("device-to-cloud-messages/");

                    //CloudBlockBlob cloudBlockBlob = fileContainer.GetBlockBlobReference($"yourfoldername/{fileName}");
                    // Create a container called 'quickstartblobs' and append a GUID value to it to make the name unique.
                    // cloudBlobContainer = cloudBlobClient.GetContainerReference("quickstartblobs" + Guid.NewGuid().ToString());

                    cloudBlobContainer = cloudBlobClient.GetContainerReference("device-to-cloud-messages");
                    await cloudBlobContainer.CreateIfNotExistsAsync();

                    Console.WriteLine("Created container '{0}'", "test");
                    Console.WriteLine();

                    // Set the permissions so the blobs are public.
                    BlobContainerPermissions permissions = new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    };
                    await cloudBlobContainer.SetPermissionsAsync(permissions);

                    // Create a file in your local MyDocuments folder to upload to a blob.
                    string localPath     = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    string localFileName = "tema12.json";
                    sourceFile = Path.Combine(localPath, localFileName);
                    // Write text to the file.

                    string jsonMes = "{\"_id\":\"19\",\"NodeId\":\"1277\",\"SourceTimestamp\":\"2018-11-05T10:57:48.1305518Z\",\"Value\":\"-0.165\"}";
                    File.WriteAllText(sourceFile, jsonMes);

                    Console.WriteLine("Temp file = {0}", sourceFile);
                    Console.WriteLine("Uploading to Blob storage as blob '{0}'", localFileName);
                    Console.WriteLine();

                    // Get a reference to the blob address, then upload the file to the blob.
                    // Use the value of localFileName for the blob name.
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference($"demo-hub-iot/00/{localFileName}");
                    await cloudBlockBlob.UploadFromStreamAsync(encodedMessage.GetBodyStream());

                    // List the blobs in the container.
                    Console.WriteLine("Listing blobs in container.");
                    BlobContinuationToken blobContinuationToken = null;
                    do
                    {
                        var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);

                        // Get the value of the continuation token returned by the listing call.
                        blobContinuationToken = results.ContinuationToken;
                        foreach (IListBlobItem item in results.Results)
                        {
                            Console.WriteLine(item.Uri);
                        }
                    } while (blobContinuationToken != null); // Loop while the continuation token is not null.
                    Console.WriteLine();

                    // Download the blob to a local file, using the reference created earlier.
                    // Append the string "_DOWNLOADED" before the .txt extension so that you can see both files in MyDocuments.
                    destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");
                    Console.WriteLine("Downloading blob to {0}", destinationFile);
                    Console.WriteLine();
                    await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create);
                }
                catch (StorageException ex)
                {
                    Console.WriteLine("Error returned from the service: {0}", ex.Message);
                }
            }
            else
            {
                Console.WriteLine(
                    "A connection string has not been defined in the system environment variables. " +
                    "Add a environment variable named 'storageconnectionstring' with your storage " +
                    "connection string as a value.");
            }
        }
		public static Task SetPermissionsAsync(this CloudBlobContainer container, BlobContainerPermissions permissions) {
			return Task.Factory.FromAsync(
				(cb, state) => container.BeginSetPermissions(permissions, cb, state),
				ar => container.EndSetPermissions(ar),
				null);
		}
 /// <summary>
 /// Reads the share access policies from a stream in XML.
 /// </summary>
 /// <param name="inputStream">The stream of XML policies.</param>
 /// <param name="permissions">The permissions object to which the policies are to be written.</param>
 public static void ReadSharedAccessIdentifiers(Stream inputStream, BlobContainerPermissions permissions)
 {
     Response.ReadSharedAccessIdentifiers(permissions.SharedAccessPolicies, new BlobAccessPolicyResponse(inputStream));
 }