Example #1
0
 public async Task DeleteAsync(T entity)
 {
     CloudBlockBlob blob = _container.GetBlockBlobReference(entity.Id);
     await blob.DeleteIfExistsAsync();
 }
Example #2
0
        public static async System.Threading.Tasks.Task <ActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "ResetAll")] HttpRequest req,
            [CosmosDB(ConnectionStringSetting = "CosmosDB")] DocumentClient client)
        {
            //Credentials
            SearchIndexClient  indexClient        = new SearchIndexClient("jfk-search-service-qymjpzort5hho", "jfkindex", new SearchCredentials("023DB82430FFA416AD39EEF8A6FDFF2A"));
            StorageCredentials storageCredentials = new StorageCredentials("jfkstorageqymjpzort5hho",
                                                                           "CamEKgqVaylmQta0aUTqN8vUy/xvUewVYZOrBvF1mh85zlgtj3fm7YheYRgoB6paMp+VcFUpTRIlow2VHlyCww==");
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, useHttps: true);
            CloudBlobContainer  container      = storageAccount.CreateCloudBlobClient().GetContainerReference("datum");

            //wait to execute delete "Index-batch"
            while (true)
            {
                DocumentSearchResult <Microsoft.Azure.Search.Models.Document> searchResult = indexClient.Documents.Search <Microsoft.Azure.Search.Models.Document>(string.Empty);
                List <string> azureDocsToDelete =
                    searchResult.Results
                    .Select(r => r.Document["id"].ToString()).ToList();
                if (azureDocsToDelete.Count != 0)
                {
                    try
                    {
                        var batch  = IndexBatch.Delete("id", azureDocsToDelete);
                        var result = indexClient.Documents.Index(batch);
                    }
                    catch (IndexBatchException ex)
                    {
                        throw new Exception($"Failed to reset the index: {string.Join(", ", ex.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key))}");
                    }
                }
                else
                {
                    break;
                }
            }
            //delete all blockblobs "datum-container"
            List <string>     blobs         = new List <string>();
            BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(null);

            foreach (IListBlobItem item in resultSegment.Results)
            {
                CloudBlockBlob blob = (CloudBlockBlob)item;
                blobs.Add(blob.Name);
            }
            foreach (var file in blobs)
            {
                CloudBlockBlob blob = container.GetBlockBlobReference(file);
                await blob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);
            }
            //create an instance "TaskDatabase-collection"
            Database           db   = client.CreateDatabaseQuery().Where(d => d.Id == "taskDatabase").AsEnumerable().SingleOrDefault();
            DocumentCollection coll = client.CreateDocumentCollectionQuery(db.SelfLink).Where(c => c.Id == "TaskCollection").ToList().SingleOrDefault();
            var docs = client.CreateDocumentQuery(coll.DocumentsLink);

            foreach (var doc in docs)
            {
                await client.DeleteDocumentAsync(doc.SelfLink);
            }
            Console.WriteLine("11111");
            //delete collection "Recorrido-container"
            DocumentCollection collection = client.CreateDocumentCollectionQuery(db.SelfLink).Where(a => a.Id == "recorrido").ToList().SingleOrDefault();
            var docs2 = client.CreateDocumentQuery(collection.DocumentsLink);

            foreach (var doc2 in docs2)
            {
                await client.DeleteDocumentAsync(doc2.SelfLink, new RequestOptions { PartitionKey = new PartitionKey(doc2.Id) });
            }
            Console.WriteLine("2222");
            return((ActionResult) new OkObjectResult($" success executed function reset All "));
        }
Example #3
0
        //generate NumToAdd devices and add them to the hub
        // to do this, generate each identity
        // * include authentication keys
        // * write the device info to a block blob
        // * import the devices into the identity registry by calling the import job
        public static async Task GenerateAndAddDevices(string hubConnectionString,
                                                       CloudBlobContainer cloudBlobContainer,
                                                       string containerURI, int NumToAdd, string devicesToAdd)
        {
            //generate reference for list of new devices you're going to add, will write list to this blob
            CloudBlockBlob generatedListBlob = cloudBlobContainer.GetBlockBlobReference(devicesToAdd);

            // define serializedDevices as a generic list<string>
            List <string> serializedDevices = new List <string>();

            for (var i = 1; i <= NumToAdd; i++)
            {
                // Create device name with this format: Hub_00000000 + a new guid.
                // This should be large enough to display the largest number (1 million).
                //string deviceName = "Hub_" + i.ToString("D8") + "-" + Guid.NewGuid().ToString();
                string deviceName = $"Hub_{i.ToString("D8")}-{Guid.NewGuid().ToString()}";

                System.Diagnostics.Debug.Print("device = '{0}'", deviceName);
                // Create a new ExportImportDevice.
                // CryptoKeyGenerator is in the Microsoft.Azure.Devices.Common namespace.
                var deviceToAdd = new ExportImportDevice()
                {
                    Id             = deviceName,
                    Status         = DeviceStatus.Enabled,
                    Authentication = new AuthenticationMechanism()
                    {
                        SymmetricKey = new SymmetricKey()
                        {
                            PrimaryKey   = CryptoKeyGenerator.GenerateKey(32),
                            SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
                        }
                    },
                    // This indicates that the entry should be added as a new device.
                    ImportMode = ImportMode.Create
                };

                // Add device to the list as a serialized object.
                serializedDevices.Add(JsonConvert.SerializeObject(deviceToAdd));
            }

            // Now have a list of devices to be added, each one has been serialized.
            // Write the list to the blob.
            var sb = new StringBuilder();

            serializedDevices.ForEach(serializedDevice => sb.AppendLine(serializedDevice));

            // Before writing the new file, make sure there's not already one there.
            await generatedListBlob.DeleteIfExistsAsync();

            // Write list of serialized objects to the blob.
            using (CloudBlobStream stream = await generatedListBlob.OpenWriteAsync())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
                for (var i = 0; i < bytes.Length; i += 500)
                {
                    int length = Math.Min(bytes.Length - i, 500);
                    await stream.WriteAsync(bytes, i, length);
                }
            }

            // Should now have a file with all the new devices in it as serialized objects in blob storage.

            // generatedListBlob has the list of devices to be added as serialized objects.

            // Call import using the blob to add the new devices.
            // Log information related to the job is written to the same container.
            // This normally takes 1 minute per 100 devices.

            // First, initiate an import job.
            // This reads in the rows from the text file and writes them to IoT Devices.
//**USE THIS TO ADD FROM FILE**
            JobProperties   importJob       = new JobProperties();
            RegistryManager registryManager =
                RegistryManager.CreateFromConnectionString(hubConnectionString);

            try
            {
                // First URL is the container to import from; the file must be called devices.txt
                // Second URL points to the container to write errors to as a block blob.
                // This lets you import the devices from any file name. Since we wrote the new
                //   devices to [devicesToAdd], need to read the list from there as well.
                importJob =
                    await registryManager.ImportDevicesAsync(containerURI, containerURI, devicesToAdd);

                // This will catch any errors if something bad happens to interrupt the job.
                while (true)
                {
                    importJob = await registryManager.GetJobAsync(importJob.JobId);

                    if (importJob.Status == JobStatus.Completed ||
                        importJob.Status == JobStatus.Failed ||
                        importJob.Status == JobStatus.Cancelled)
                    {
                        // Job has finished executing
                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("description = {0}", ex.Message);
            }
        }
        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>A Task object.</returns>
        private static async Task BasicStorageBlockBlobOperationsAsync()
        {
            const string ImageToUpload = "HelloWorld.png";
            string       containerName = ContainerPrefix + Guid.NewGuid();

            // Retrieve storage account information from connection string
            CloudStorageAccount storageAccount = Common.CreateStorageAccountFromConnectionString();

            // Create a blob client for interacting with the blob service.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Create a container for organizing blobs within the storage account.
            Console.WriteLine("1. Creating Container");
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            try
            {
                // The call below will fail if the sample is configured to use the storage emulator in the connection string, but
                // the emulator is not running.
                // Change the retry policy for this call so that if it fails, it fails quickly.
                BlobRequestOptions requestOptions = new BlobRequestOptions()
                {
                    RetryPolicy = new NoRetry()
                };
                await container.CreateIfNotExistsAsync(requestOptions, null);
            }
            catch (StorageException)
            {
                Console.WriteLine("If you are running with the default connection string, 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);

            // Set the blob's content type so that the browser knows to treat it as an image.
            blockBlob.Properties.ContentType = "image/png";
            await blockBlob.UploadFromFileAsync(ImageToUpload);

            // List all the blobs in the container.
            /// Note that the ListBlobs method is called synchronously, for the purposes of the sample. However, in a real-world
            /// application using the async/await pattern, best practices recommend using asynchronous methods consistently.
            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. This line is not strictly necessary as the container is deleted in the next call.
            // It is included for the purposes of the example.
            Console.WriteLine("6. Delete block blob and all of its snapshots");
            await blockBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);

            // Note that deleting the container also deletes any blobs in the container, and their snapshots.
            // In the case of the sample, we delete the blob and its snapshots, and then the container,
            // to show how to delete each kind of resource.
            Console.WriteLine("7. Delete Container");
            await container.DeleteIfExistsAsync();
        }
        public async Task <IActionResult> Edit(int id, [Bind("ID,Category,Name,Brand,PurchaseDate,Price,WornTimes,ImageUrl,FileName,UserId")] Wardrobe wardrobe, List <IFormFile> files, string filename)
        {
            if (id != wardrobe.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var filepath = Path.GetTempFileName();

                foreach (var FormFile in files)
                {
                    if (FormFile.Length <= 0)
                    {
                        TempData["editmessage"] = "Please upload a proper image file";
                    }

                    else
                    {
                        if (filename != null)
                        {
                            //delete file from blob
                            CloudBlobContainer container1 = GetCloudBlobContainer();
                            CloudBlockBlob     blobfile   = container1.GetBlockBlobReference(filename);
                            string             name       = blobfile.Name;
                            var result = blobfile.DeleteIfExistsAsync().Result;

                            if (result == false)
                            {
                                TempData["message"] = "Unable to delete file";
                            }
                            else
                            {
                                TempData["message"] = "File is deleted";
                            }
                        }
                        //first all, get the container information
                        CloudBlobContainer container = GetCloudBlobContainer();
                        //give a name for the blob
                        CloudBlockBlob blob = container.GetBlockBlobReference(Path.GetFileName(FormFile.FileName));
                        try
                        {
                            using (var stream = FormFile.OpenReadStream())
                            {
                                await blob.UploadFromStreamAsync(stream);
                            }
                        }
                        catch (Exception ex)
                        {
                            TempData["message"] = ex.ToString();
                        }

                        // get the uri of the specific uploaded blob and save it
                        var blobUrl = blob.Uri.AbsoluteUri;
                        wardrobe.ImageUrl = blobUrl.ToString();
                        wardrobe.FileName = FormFile.FileName.ToString();
                        _context.Update(wardrobe);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction(nameof(Index)));
                    }
                }
                try
                {
                    _context.Update(wardrobe);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WardrobeExists(wardrobe.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(wardrobe));
        }
Example #6
0
        public static async Task Run(
            [BlobTrigger("review-photos/{fileName}.mp4", Connection = "AzureWebJobsStorage")] CloudBlockBlob inputBlob,
            string fileName,
            TraceWriter log)
        {
            try
            {
                fileName = $"{fileName}.mp4";

                log.Info($"C# Blob trigger function Processed blob\n Name:{fileName}");

                if (!inputBlob.Metadata.ContainsKey("reviewId"))
                {
                    log.Warning("No review id metadata!");
                    await inputBlob.DeleteIfExistsAsync();
                }

                string reviewId  = inputBlob.Metadata["reviewId"];
                string assetName = inputBlob.Name;

                InitializeCloudMediaContext();

                // 1. Copy BLOB into Input Asset
                IAsset thumbAsset = await CreateAssetFromBlobAsync(inputBlob, $"thumb-{fileName}", log);

                log.Info("Deleting the source asset from the input container");
                await inputBlob.DeleteIfExistsAsync();

                // 2. Create an encoding job

                // Declare a new encoding job with the Standard encoder
                IJob job = context.Jobs.Create("Build Reviewer - Function Kickoff");

                // Get a media processor reference, and pass to it the name of the
                // processor to use for the specific task.
                IMediaProcessor processor = GetLatestMediaProcessorByName("Media Encoder Standard");

                // 3. Create an encoding task

                // grab preset encoding info that will create a video & a thumbnail
                var thumbnailPreset = VideoEncodingPresetGenerator.Thumbnail().ToJson();

                // create a task that does the encoding
                ITask thumbnailTask = job.Tasks.AddNew("Thumbnail encode", processor, thumbnailPreset, TaskOptions.None);
                thumbnailTask.Priority = 100;

                // Make sure there's an input asset to encode
                thumbnailTask.InputAssets.Add(thumbAsset);

                var outAssetName = $"thumbnail-{fileName}";

                // Define the output asset
                thumbnailTask.OutputAssets.AddNew(outAssetName, AssetCreationOptions.None);

                // Submit the job
                job.Submit();
                log.Info("Job Submitted");

                // 3. Monitor the job
                while (true)
                {
                    job.Refresh();

                    // Refresh every 5 seconds
                    await Task.Delay(5000);

                    log.Info($"Job: {job.Id}    State: {job.State.ToString()}");

                    if (job.State == JobState.Error || job.State == JobState.Finished || job.State == JobState.Canceled)
                    {
                        break;
                    }
                }

                if (job.State == JobState.Finished)
                {
                    log.Info($"Job {job.Id} is complete.");

                    // Call a webhook
                    var msg = new VideoPublishMessage {
                        AssetName = outAssetName, ReviewId = reviewId
                    };

                    var client = new HttpClient();
                    await client.PostAsJsonAsync <VideoPublishMessage>(webhookEndpoint, msg);
                }
                else if (job.State == JobState.Error)
                {
                    log.Error("Job Failed with Error. ");
                    throw new Exception("Job failed encoding .");
                }
            }
            catch (Exception ex)
            {
                log.Error($"An exception occurred: {ex.Message}");
            }

            // Write to a queue
            log.Info("All done!!");
        }
Example #7
0
        //private async Task btnFileQuery_Click()
        //{
        //    StorageFile file = null;
        //    if (webcam.IsInitialized())
        //    {
        //        // Stores current frame from webcam feed in a temporary folder
        //        file = await webcam.CapturePhoto();
        //        FaceQuery(file);
        //    }
        //    else
        //    {
        //        if (!webcam.IsInitialized())
        //        {
        //            // The webcam has not been fully initialized for whatever reason:
        //            Debug.WriteLine("Unable to analyze visitor at door as the camera failed to initlialize properly.");
        //            await speech.Read(SpeechContants.NoCameraMessage);
        //        }
        //    }

        //    FaceQuery(file);
        //    btnFileQuery.IsEnabled = true;
        //}
        private async void FaceQuery(StorageFile file)
        {
            CloudBlockBlob blob         = null;
            string         blobFileName = null;

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

                bitmapImage.SetSource(fileStream);

                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)
                    {
                        await speech.Read(SpeechContants.VisitorNotRecognizedMessage);
                    }
                    else
                    {
                        UnlockDoor(string.Join(", ", names.ToArray()));
                    }
                }
                else
                {
                    string responseBody = await response.Content.ReadAsStringAsync();

                    globals.ShowJsonErrorPopup(responseBody);
                }

                await blob.DeleteAsync();

                progressRingMainPage.IsActive = false;
            }
        }
Example #8
0
        public async Task <string> CreateUploadedImageAsync(HttpPostedFileBase file, string fileName, bool resizeImage = false, int width = 0, int height = 0)
        {
            if (file == null)
            {
                return(null);
            }

            string imageFullPath = null;

            try
            {
                var            _fileName = file.FileName;
                var            imageName = fileName + Path.GetExtension(_fileName);
                CloudBlockBlob originalcloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(_fileName);
                CloudBlockBlob cloudBlockBlob         = cloudBlobContainer.GetBlockBlobReference(imageName);
                cloudBlockBlob.Properties.ContentType = file.ContentType;

                if (resizeImage)
                {
                    Bitmap bitmap = new Bitmap(file.InputStream);

                    int oldWidth  = bitmap.Width;
                    int oldHeight = bitmap.Height;

                    GraphicsUnit units   = System.Drawing.GraphicsUnit.Pixel;
                    RectangleF   r       = bitmap.GetBounds(ref units);
                    Size         newSize = new Size();

                    float expectedWidth  = r.Width;
                    float expectedHeight = r.Height;
                    float dimesion       = r.Width / r.Height;

                    if (width < r.Width)
                    {
                        expectedWidth  = width;
                        expectedHeight = expectedWidth / dimesion;
                    }
                    else if (height < r.Height)
                    {
                        expectedHeight = height;
                        expectedWidth  = dimesion * expectedHeight;
                    }
                    if (expectedWidth > width)
                    {
                        expectedWidth  = width;
                        expectedHeight = expectedHeight / expectedWidth;
                    }
                    //else if (nPozadovanaVyska > height)
                    //{
                    //	expectedHeight = height;
                    //	expectedWidth = dimesion * expectedHeight;
                    //}
                    newSize.Width  = (int)Math.Round(expectedWidth);
                    newSize.Height = (int)Math.Round(expectedHeight);

                    Bitmap b = new Bitmap(bitmap, newSize);

                    Image  img  = (Image)b;
                    byte[] data = ImageToByte(img);

                    cloudBlockBlob.UploadFromByteArray(data, 0, data.Length);
                    await originalcloudBlockBlob.DeleteIfExistsAsync(); //remove old if exist.
                }
                else
                {
                    await cloudBlockBlob.UploadFromStreamAsync(file.InputStream);
                }

                imageFullPath = cloudBlockBlob.Uri.ToString();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("An error ocurred in CreateUploadedImageAsync method.", ex);
            }
            finally
            {
                Console.WriteLine("CreateUploadedImageAsync Finish.");
            }

            return(imageFullPath);
        }
Example #9
0
        private static async Task RunAddPackageAsync(PackageOperation packageOperation, CloudBlockBlob packageBlob, ILogger log, List <IndexAction <PackageDocument> > indexActions)
        {
            var packagesToIndex = new List <PackageDocument>();

            log.LogInformation("Downloading package {packageId}@{packageVersionNormalized} for indexing...",
                               packageOperation.Id, packageOperation.Version);

            using (var packageInputStream = await HttpClient.GetStreamAsync(packageOperation.PackageUrl))
                using (var packageInputSeekableStream = TemporaryFileStream.Create())
                {
                    await packageInputStream.CopyToAsync(packageInputSeekableStream);

                    packageInputSeekableStream.Position = 0;

                    log.LogInformation("Finished downloading package {packageId}@{packageVersionNormalized} for indexing...",
                                       packageOperation.Id, packageOperation.Version);

                    using (var nugetPackage = new PackageArchiveReader(packageInputSeekableStream))
                    {
                        log.LogInformation("Analyzing package {packageId}@{packageVersionNormalized}...",
                                           packageOperation.Id, packageOperation.Version);

                        // Get some metadata
                        var nuspecReader    = nugetPackage.NuspecReader;
                        var packageIdentity = nuspecReader.GetIdentity();
                        var packageSummary  = nuspecReader.GetDescription();
                        if (string.IsNullOrEmpty(packageSummary))
                        {
                            packageSummary = nuspecReader.GetSummary();
                        }

                        var packageToIndex = new PackageDocument(
                            packageIdentity.Id,
                            packageIdentity.Version.ToNormalizedString(),
                            packageIdentity.Version.OriginalVersion,
                            nuspecReader.GetTitle(),
                            packageSummary,
                            nuspecReader.GetAuthors(),
                            nuspecReader.GetTags(),
                            nuspecReader.GetIconUrl(),
                            nuspecReader.GetLicenseUrl(),
                            nuspecReader.GetProjectUrl(),
                            packageOperation.Published,
                            AuxiliaryNuGetData.GetDownloadCount(packageIdentity.Id),
                            packageOperation.IsListed,
                            packageIdentity.Version.IsPrerelease);

                        var targetFrameworks = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        var typeNames        = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                        var frameworkSpecificGroups = nugetPackage.GetReferenceItems();
                        foreach (var frameworkSpecificGroup in frameworkSpecificGroups)
                        {
                            // Get some metadata
                            var targetFramework = frameworkSpecificGroup.TargetFramework.GetShortFolderName();
                            targetFrameworks.Add(targetFramework);

                            log.LogInformation(
                                "Collecting information for {packageId}@{packageVersionNormalized} and framework {targetFramework}...",
                                packageOperation.Id, packageOperation.Version, targetFramework);

                            // Collect assembly data
                            foreach (var item in frameworkSpecificGroup.Items)
                            {
                                var entry     = nugetPackage.GetEntry(item);
                                var entryName = item;

                                log.LogInformation(
                                    "Collecting assembly information from {entryName} for {packageId}@{packageVersionNormalized} and framework {targetFramework}...",
                                    entryName, packageOperation.Id, packageOperation.Version, targetFramework);

                                using (var assemblyStream = entry.Open())
                                    using (var assemblySeekableStream = TemporaryFileStream.Create())
                                    {
                                        await assemblyStream.CopyToAsync(assemblySeekableStream);

                                        assemblySeekableStream.Position = 0;

                                        using (var portableExecutableReader = new PEReader(assemblySeekableStream))
                                        {
                                            var metadataReader = portableExecutableReader.GetMetadataReader();
                                            foreach (var typeDefinition in metadataReader.TypeDefinitions.Select(metadataReader
                                                                                                                 .GetTypeDefinition))
                                            {
                                                if (!typeDefinition.Attributes.HasFlag(TypeAttributes.Public))
                                                {
                                                    continue;
                                                }

                                                var typeNamespace = metadataReader.GetString(typeDefinition.Namespace);
                                                var typeName      = metadataReader.GetString(typeDefinition.Name);

                                                if (typeName.StartsWith("<") || typeName.StartsWith("__Static") ||
                                                    typeName.Contains("c__DisplayClass"))
                                                {
                                                    continue;
                                                }

                                                log.LogDebug(
                                                    "{packageId}@{packageVersionNormalized}, framework {targetFramework}, entry {entryName}: adding {namespace}.{type}",
                                                    packageOperation.Id, packageOperation.Version, targetFramework, entryName, typeNamespace, typeName);

                                                typeNames.Add($"{typeNamespace}.{typeName}");
                                            }
                                        }
                                    }

                                log.LogInformation(
                                    "Finished collecting assembly information from {entryName} for {packageId}@{packageVersionNormalized} and framework {targetFramework}.",
                                    entryName, packageOperation.Id, packageOperation.Version, targetFramework);
                            }

                            log.LogInformation(
                                "Finished collecting information for {packageId}@{packageVersionNormalized} and framework {targetFramework}.",
                                packageOperation.Id, packageOperation.Version, targetFramework);
                        }

                        packageToIndex.TargetFrameworks = targetFrameworks.ToHashSet();
                        packageToIndex.TypeNames        = typeNames.ToHashSet();

                        log.LogInformation("Finished analyzing package {packageId}@{packageVersionNormalized}.",
                                           packageOperation.Id, packageOperation.Version);

                        // Build index
                        log.LogInformation(
                            "Creating index actions for package {packageId}@{packageVersionNormalized}...",
                            packageOperation.Id, packageOperation.Version);

                        // Add to index blob
                        packagesToIndex.Add(packageToIndex);

                        // Add to index
                        indexActions.Add(IndexAction.MergeOrUpload(packageToIndex));

                        log.LogInformation(
                            "Finished creating index actions for package {packageId}@{packageVersionNormalized}.",
                            packageOperation.Id, packageOperation.Version);

                        log.LogInformation("Finished analyzing package {packageId}@{packageVersionNormalized}.",
                                           packageOperation.Id, packageOperation.Version);
                    }
                }

            log.LogInformation("Storing index blob for package {packageId}@{packageVersionNormalized}...",
                               packageOperation.Id, packageOperation.Version);

            // Store index blob
            try
            {
                await packageBlob.DeleteIfExistsAsync();

                using (var jsonStream = await packageBlob.OpenWriteAsync())
                    using (var jsonWriter = new StreamWriter(jsonStream))
                    {
                        JsonSerializer.Serialize(jsonWriter, packagesToIndex);
                    }

                log.LogInformation("Finished storing index blob for package {packageId}@{packageVersionNormalized}.",
                                   packageOperation.Id, packageOperation.Version);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Error storing index blob for package {packageId}@{packageVersionNormalized}.",
                             packageOperation.Id, packageOperation.Version);
            }
        }
Example #10
0
        private async Task ProcessTransactions(string sourceAzid, CloudBlobDirectory sourceDirectory, IEnumerable <TagTransactionEntity> tagTransactions, SoftwareIdentity indexJsonTag, SoftwareIdentity indexXmlTag)
        {
            var storage = this.Connection.ConnectToTagStorage();

            var tagsTable = new TagTable(this.Connection);

            //var tagsBatch = new AzureBatch(tagsTable.Table);

            var redirectsTable = new DownloadRedirectsTable(this.Connection);

            var batchTasks = new List <AzureBatch>();

            var redirectsTasks = new List <Task>();

            var addedTags = new List <AddedTagResult>();

            var updatedTags = new List <UpdatedTagResult>();

            var deleteTags = new List <DeleteTagResult>();

            foreach (var tagTx in tagTransactions)
            {
                var op = (TagTransactionOperation)Enum.Parse(typeof(TagTransactionOperation), tagTx.Operation);

                switch (op)
                {
                case TagTransactionOperation.Create:
                {
                    var add = await this.CreateTag(sourceAzid, sourceDirectory, tagTx);

                    addedTags.Add(add);

                    var batch = new AzureBatch(tagsTable.Table);
                    batch.Create(add.Tag);
                    batch.Upsert(add.PrimaryTag);
                    batchTasks.Add(batch);

                    var tasks = CreateRedirects(redirectsTable.Table, add.Redirects);
                    redirectsTasks.AddRange(tasks);
                }
                break;

                case TagTransactionOperation.Update:
                {
                    var update = await this.UpdateTag(sourceAzid, sourceDirectory, tagsTable, tagTx);

                    updatedTags.Add(update);

                    var batch = new AzureBatch(tagsTable.Table);
                    batch.Create(update.Tag);
                    batch.Upsert(update.PrimaryTag);
                    batchTasks.Add(batch);

                    var tasks = CreateRedirects(redirectsTable.Table, update.Redirects);
                    redirectsTasks.AddRange(tasks);
                }
                break;

                case TagTransactionOperation.Delete:
                {
                    var delete = DeleteTag(sourceAzid, tagsTable, tagTx);

                    deleteTags.Add(delete);

                    var batch = new AzureBatch(tagsTable.Table);
                    batch.Update(delete.Tag);
                    batchTasks.Add(batch);
                }
                break;
                }
            }

            foreach (var batch in batchTasks)
            {
                await batch.WhenAll();
            }

            await Task.WhenAll(redirectsTasks);

            if (this.UpdateIndexTags(indexJsonTag, indexXmlTag, addedTags, updatedTags, deleteTags))
            {
                await this.WriteIndexTags(indexJsonTag, indexXmlTag, sourceDirectory);
            }

            var deleteTasks = new List <Task>(deleteTags.Count + 1);

            foreach (var deleteResult in deleteTags)
            {
                var blobJson = new CloudBlockBlob(deleteResult.DeleteSourceUris.JsonUri, storage.Credentials);

                var blobXml = new CloudBlockBlob(deleteResult.DeleteSourceUris.XmlUri, storage.Credentials);

                deleteTasks.Add(blobJson.DeleteIfExistsAsync());

                deleteTasks.Add(blobXml.DeleteIfExistsAsync());
            }

            await Task.WhenAll(deleteTasks);
        }
Example #11
0
        //<summary>
        //Function helps in renaming task.
        //</summary>
        public static async Task <bool> RenameHelperAsync(TableResult retreiveResult, string newFileName)
        {
            try
            {
                string scrapeName         = ((TableRecord)retreiveResult.Result).ScrapeName;
                string container          = ((TableRecord)retreiveResult.Result).ContainerName;
                string storageAccountName = ((TableRecord)retreiveResult.Result).StorageAccountName;
                string storageAccessKey   = ((TableRecord)retreiveResult.Result).KeyValue;

                if (container != null)
                {
                    string StorageConnectionString     = "DefaultEndpointsProtocol=https;AccountName=afimssav;AccountKey=ZiLCuZ6WvK8aZYLzXUNbTn+Tjl1hhPMaOeBhIdi00Urk8nTl3fwAsyCkXOXXcYzsjlBDDNG1Sahgte0q/3SJgQ==;EndpointSuffix=core.windows.net";
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageConnectionString);
                    CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer  containerName  = blobClient.GetContainerReference(container);
                    switch (((TableRecord)retreiveResult.Result).Type)
                    {
                    case "CloudBlockBlob":
                    {
                        string         fileName = scrapeName;
                        CloudBlockBlob blobCopy = containerName.GetBlockBlobReference(newFileName);
                        if (!await blobCopy.ExistsAsync())
                        {
                            CloudBlockBlob blob = containerName.GetBlockBlobReference(fileName);

                            if (await blob.ExistsAsync())
                            {
                                await blobCopy.StartCopyAsync(blob);

                                await blob.DeleteIfExistsAsync();

                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        break;
                    }

                    case "CloudBlobContainer":
                    {
                        {
                            var permissions = containerName.GetPermissions();
                            permissions.PublicAccess = BlobContainerPublicAccessType.Off;
                            return(true);
                        }
                    }

                    case "CloudBlobDirectory":
                    {
                        break;
                    }
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Source);
                Console.WriteLine(ex.StackTrace);
                return(false);
            }
        }
Example #12
0
 public async Task DeleteImageAsync(string name)
 {
     CloudBlockBlob blockBlob = _container.GetBlockBlobReference(name);
     await blockBlob.DeleteIfExistsAsync();
 }
Example #13
0
        public static async Task Run([BlobTrigger("working/{set}/{controlFileName}.json", Connection = AzureConstants.BlobStorageConnectionStringName)] CloudBlockBlob controlBlob,
                                     string set, string controlFileName, IBinder binder, TraceWriter log)
        {
            // 1. Read the text of the control file
            var controlFileText = await controlBlob.DownloadTextAsync();

            var control = JsonConvert.DeserializeObject <ProcessingControl>(controlFileText);

            log.Info($"Read control file {controlFileName}.json for image file {set}/{control.File} - contains {control.Instructions.Count} processing instructions");

            // 2. Form the path to the image file
            var imageFilePath = $"working/{set}/{control.File}";
            var imageFileBlob = await binder.BindToBlockBlob(imageFilePath, AzureConstants.BlobStorageConnectionStringName);

            // 3. Read the bytes of the image file
            var blobStream = new MemoryStream();
            await imageFileBlob.DownloadToStreamAsync(blobStream);

            blobStream.Position = 0;

            // 4. Check if there are more instructions
            if (control.Instructions.Count > 0)
            {
                // 4a. Dequeue and perform the next processing instruction
                var nextInstruction = control.Instructions.Dequeue();
                var nextImageBytes  = ImageProcessor.ProcessInstruction(nextInstruction, blobStream);

                if (nextInstruction.Operation != ProcessingOperation.ChangeFormat)
                {
                    // 4b. Write the bytes of the image
                    await imageFileBlob.UploadFromByteArrayAsync(nextImageBytes, 0, nextImageBytes.Length);

                    // 4c. Write the text of the control file
                    var newControlFileJson = JsonConvert.SerializeObject(control);
                    await controlBlob.UploadTextAsync(newControlFileJson);
                }
                else
                {
                    // we've changed the format - so the filename needs to change
                    var shortNewImageFilename = $"{Path.GetFileNameWithoutExtension(imageFilePath)}.{nextInstruction.Arguments[0]}";
                    var newImageFilename      = $"working/{set}/{shortNewImageFilename}";
                    // change the name in the control file
                    control.File = shortNewImageFilename;
                    // delete the original file
                    await imageFileBlob.DeleteIfExistsAsync();

                    // get the new blob
                    var newImageFileBlob = await binder.BindToBlockBlob(newImageFilename, AzureConstants.BlobStorageConnectionStringName);

                    // write the new image bytes
                    await newImageFileBlob.UploadFromByteArrayAsync(nextImageBytes, 0, nextImageBytes.Length);

                    // write the updated control file
                    var newControlFileJson = JsonConvert.SerializeObject(control);
                    await controlBlob.UploadTextAsync(newControlFileJson);
                }
            }
            else
            {
                // 5. Form the path of the output file
                var outputFilePath = $"output/{set}/{control.File}";
                log.Info($"No processing to perform - writing to output file {outputFilePath}");

                var outputFile = await binder.BindToBlockBlob(outputFilePath, AzureConstants.BlobStorageConnectionStringName);

                // 6. Write the final output image file
                await outputFile.UploadFromStreamAsync(blobStream);

                // 7. Remove the working image file
                await imageFileBlob.DeleteIfExistsAsync();

                // 8. Remove the control file
                await controlBlob.DeleteIfExistsAsync();
            }
        }
Example #14
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string responseMessage;

            string blobName = req.Query["blobName"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            blobName = blobName ?? data?.blobName;

            string sourceStorage = Environment.GetEnvironmentVariable("NewImageSourceStorage");

            CloudStorageAccount sourceStorageAccount = CloudStorageAccount.Parse(sourceStorage);

            string             imageContainerName = Environment.GetEnvironmentVariable("ImageContainerName");
            CloudBlobClient    imageBlobClient    = sourceStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer imageContainer     = imageBlobClient.GetContainerReference(imageContainerName);
            CloudBlockBlob     imageBlob          = imageContainer.GetBlockBlobReference(blobName);

            ImageMetadata imageData = new ImageMetadata()
            {
                timestamp        = DateTime.Now,
                uploadedFileName = blobName,
                id = Path.GetFileNameWithoutExtension(blobName)
            };

            using (MemoryStream blobMemStream = new MemoryStream())
            {
                await imageBlob.DownloadToStreamAsync(blobMemStream);


                byte[] byteData = blobMemStream.ToArray();

                log.LogInformation("Image Byte Array:" + byteData);

                var client = new HttpClient();

                // Request headers - replace this example key with your valid Prediction-Key.

                client.DefaultRequestHeaders.Add("Prediction-Key", Environment.GetEnvironmentVariable("CustomVisionPredictionKey"));

                // Prediction URL - replace this example URL with your valid Prediction URL.

                string rootUrl   = Environment.GetEnvironmentVariable("CustomVisionRootUrl");
                string iteration = Environment.GetEnvironmentVariable("CustomVisionIteration");
                string url       = rootUrl + iteration + "/image";

                HttpResponseMessage response;

                // Request body. Try this sample with a locally stored image.

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response = await client.PostAsync(url, content);

                    string responseBody = await response.Content.ReadAsStringAsync();

                    imageData = ProcessCustomVisionResults(responseBody, imageData);

                    Console.WriteLine(responseBody);
                }

                if (imageData.isValidatedIssue)
                {
                    log.LogInformation("Uploaded Image has been identified as an issue");

                    string             metaContainerName = Environment.GetEnvironmentVariable("ImageMetadataContainer");
                    CloudBlobClient    metaBlobClient    = sourceStorageAccount.CreateCloudBlobClient();
                    CloudBlobContainer metaContainer     = metaBlobClient.GetContainerReference(metaContainerName);
                    await metaContainer.CreateIfNotExistsAsync();

                    string         newMetaJson = System.Text.Json.JsonSerializer.Serialize <ImageMetadata>(imageData);
                    CloudBlockBlob newMetaBlob = metaContainer.GetBlockBlobReference(imageData.id + ".json");
                    await newMetaBlob.UploadTextAsync(newMetaJson);

                    responseMessage = imageData.id;
                }
                else
                {
                    log.LogInformation("Uploaded Image was not identified as an Issue. Removing image from upload container...");
                    await imageBlob.DeleteIfExistsAsync();

                    responseMessage = "-1";
                }
            }

            return(new OkObjectResult(responseMessage));
        }
        /// <summary>
        /// Generate NumToAdd devices and add them to the hub.
        /// To do this, generate each identity.
        /// Include authentication keys.
        /// Write the device info to a block blob.
        /// Import the devices into the identity registry by calling the import job.
        /// </summary>
        private async Task GenerateAndAddDevices(string hubConnectionString, string containerURI, int NumToAdd, string devicesToAdd)
        {
            int interimProgressCount = 0;
            int displayProgressCount = 1000;
            int totalProgressCount   = 0;

            // generate reference for list of new devices we're going to add, will write list to this blob
            CloudBlockBlob generatedListBlob = _cloudBlobContainer.GetBlockBlobReference(devicesToAdd);

            // define serializedDevices as a generic list<string>
            List <string> serializedDevices = new List <string>(NumToAdd);

            for (var i = 1; i <= NumToAdd; i++)
            {
                // Create device name with this format: Hub_00000000 + a new guid.
                // This should be large enough to display the largest number (1 million).
                string deviceName = $"Hub_{i:D8}_{Guid.NewGuid()}";
                Debug.Print($"device = '{deviceName}'\n");

                // Create a new ExportImportDevice.
                // CryptoKeyGenerator is in the Microsoft.Azure.Devices.Common namespace.
                var deviceToAdd = new ExportImportDevice
                {
                    Id             = deviceName,
                    Status         = DeviceStatus.Enabled,
                    Authentication = new AuthenticationMechanism
                    {
                        SymmetricKey = new SymmetricKey
                        {
                            PrimaryKey   = CryptoKeyGenerator.GenerateKey(32),
                            SecondaryKey = CryptoKeyGenerator.GenerateKey(32),
                        }
                    },
                    // This indicates that the entry should be added as a new device.
                    ImportMode = ImportMode.Create,
                };

                // Add device to the list as a serialized object.
                serializedDevices.Add(JsonConvert.SerializeObject(deviceToAdd));

                // Not real progress as you write the new devices, but will at least show *some* progress.
                interimProgressCount++;
                totalProgressCount++;
                if (interimProgressCount >= displayProgressCount)
                {
                    Console.WriteLine("Added {0} messages.", totalProgressCount);
                    interimProgressCount = 0;
                }
            }

            // Now have a list of devices to be added, each one has been serialized.
            // Write the list to the blob.
            var sb = new StringBuilder();

            serializedDevices.ForEach(serializedDevice => sb.AppendLine(serializedDevice));

            // Before writing the new file, make sure there's not already one there.
            await generatedListBlob.DeleteIfExistsAsync().ConfigureAwait(false);

            // Write list of serialized objects to the blob.
            using CloudBlobStream stream = await generatedListBlob.OpenWriteAsync().ConfigureAwait(false);

            byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
            for (var i = 0; i < bytes.Length; i += 500)
            {
                int length = Math.Min(bytes.Length - i, 500);
                await stream.WriteAsync(bytes, i, length).ConfigureAwait(false);
            }
            stream.Commit();

            Console.WriteLine("Creating and running registry manager job to write the new devices.");

            // Should now have a file with all the new devices in it as serialized objects in blob storage.
            // generatedListBlob has the list of devices to be added as serialized objects.
            // Call import using the blob to add the new devices.
            // Log information related to the job is written to the same container.
            // This normally takes 1 minute per 100 devices (according to the docs).

            // First, initiate an import job.
            // This reads in the rows from the text file and writes them to IoT Devices.
            // If you want to add devices from a file, you can create a file and use this to import it.
            //   They have to be in the exact right format.
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(hubConnectionString);

            try
            {
                // The first URL is the container to import from; the file must be called devices.txt
                // The second URL points to the container to write errors to as a block blob.
                // This lets you import the devices from any file name. Since we wrote the new
                // devices to [devicesToAdd], need to read the list from there as well.
                JobProperties importJob = await registryManager
                                          .ImportDevicesAsync(containerURI, containerURI, devicesToAdd)
                                          .ConfigureAwait(false);

                // This will catch any errors if something bad happens to interrupt the job.
                while (true)
                {
                    importJob = await registryManager.GetJobAsync(importJob.JobId).ConfigureAwait(false);

                    if (importJob.Status == JobStatus.Completed ||
                        importJob.Status == JobStatus.Failed ||
                        importJob.Status == JobStatus.Cancelled)
                    {
                        // Job has finished executing
                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Debug.Print("exception message {0}", ex.Message);
            }
        }
Example #16
0
        private async static void UploadBlockBlobs(string containerName, string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    CloudBlobContainer container = _cloudBlobClient.GetContainerReference(containerName);
                    if (await container.ExistsAsync())
                    {
                        string         name           = Path.GetFileName(path);
                        CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(name);
                        await cloudBlockBlob.DeleteIfExistsAsync();


                        List <BlobUploadObjectBytes> list = GetUploadBlobSegments(path);
                        Stopwatch stopwatch = Stopwatch.StartNew();

                        foreach (var blob in list)
                        {
                            try
                            {
                                Console.WriteLine($"[%]............Uploading {blob.Id}");
                                await cloudBlockBlob.PutBlockAsync(blob.IdBase64, new MemoryStream(blob.Contents, true), null);
                            }
                            catch
                            {
                                blob.Success = false;
                                Console.WriteLine($"[!]............{blob.IdBase64} failed to upload");
                            }
                        }

                        Console.WriteLine($"[#]............Commiting data");

                        await cloudBlockBlob.PutBlockListAsync(list.Where(x => x.Success).Select(x => x.Id));

                        stopwatch.Stop();
                        Console.WriteLine("File has been uploaded successfully. Adding some metadata...");
                        cloudBlockBlob.Metadata.Add(new KeyValuePair <string, string>("author", "Mirza Ghulam Rasyid"));
                        cloudBlockBlob.Metadata.Add(new KeyValuePair <string, string>("filename", cloudBlockBlob.Name));
                        cloudBlockBlob.Metadata.Add(new KeyValuePair <string, string>("createdDate", DateTime.UtcNow.ToString()));
                        cloudBlockBlob.Metadata.Add(new KeyValuePair <string, string>("originalFilePath", path));
                        await cloudBlockBlob.SetMetadataAsync();

                        Console.WriteLine("Metadata tags have been added.");

                        Console.WriteLine($"Upload time: {stopwatch.Elapsed}");
                    }
                    else
                    {
                        Console.WriteLine("Container is not found");
                    }
                }
                else
                {
                    Console.WriteLine("File not found");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        // This shows how to copy devices from one IoT Hub to another.
        // First, export the list from the Source hut to devices.txt (ExportDevices).
        // Next, read in that file. Each row is a serialized object;
        //   read them into the generic list serializedDevices.
        // Delete the devices.txt in blob storage, because we're going to recreate it.
        // For each serializedDevice, deserialize it, set ImportMode to CREATE,
        //   reserialize it, and write it to a StringBuilder. The ImportMode field is what
        //   tells the job framework to add each device.
        // Write the new StringBuilder to the block blob.
        //   This essentially replaces the list with a list of devices that have ImportJob = Delete.
        // Call ImportDevicesAsync, which will read in the list in devices.txt, then add each one
        //   because it doesn't already exist. If it already exists, it will write an entry to
        //   the import error log and not add the new one.
        private async Task CopyAllDevicesToNewHub(string sourceHubConnectionString, string destHubConnectionString, string containerUri, string deviceListFile)
        {
            Console.WriteLine("Exporting devices on current hub");

            // Read the devices from the hub and write them to devices.txt in blob storage.
            await ExportDevices(containerUri, sourceHubConnectionString).ConfigureAwait(false);

            // Read devices.txt which contains serialized objects.
            // Write each line to the serializedDevices list. (List<string>).
            CloudBlockBlob blockBlob = _cloudBlobContainer.GetBlockBlobReference(deviceListFile);

            // Get the URI for the blob.
            string blobUri = blockBlob.Uri.ToString();

            // Instantiate the generic list.
            var serializedDevices = new List <string>();

            Console.WriteLine("Read in list of devices from blob storage.");

            // Read the blob file of devices, import each row into serializedDevices.
            using Stream blobStream = await blockBlob.OpenReadAsync(AccessCondition.GenerateIfExistsCondition(), null, null).ConfigureAwait(false);

            using var streamReader = new StreamReader(blobStream, Encoding.UTF8);
            while (streamReader.Peek() != -1)
            {
                string line = await streamReader.ReadLineAsync().ConfigureAwait(false);

                serializedDevices.Add(line);
            }

            // Delete the blob containing the list of devices, because we're going to recreate it.
            CloudBlockBlob blobToDelete = _cloudBlobContainer.GetBlockBlobReference("devices.txt");

            Console.WriteLine("Update ImportMode to be Create.");

            // Step 1: Update each device's ImportMode to Create
            var sb = new StringBuilder();

            serializedDevices.ForEach(serializedDevice =>
            {
                // Deserialize back to an ExportImportDevice and update the import mode property.
                ExportImportDevice device = JsonConvert.DeserializeObject <ExportImportDevice>(serializedDevice);
                device.ImportMode         = ImportMode.Create;

                // Reserialize the object now that we've updated the property.
                sb.AppendLine(JsonConvert.SerializeObject(device));
            });

            // Step 2: Delete the blob if it already exists, then write the in-memory list to the blob.
            await blobToDelete.DeleteIfExistsAsync().ConfigureAwait(false);

            byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
            using CloudBlobStream stream = await blobToDelete.OpenWriteAsync().ConfigureAwait(false);

            for (var i = 0; i < bytes.Length; i += 500)
            {
                int length = Math.Min(bytes.Length - i, 500);
                await stream.WriteAsync(bytes, i, length).ConfigureAwait(false);
            }
            stream.Commit();

            Console.WriteLine("Creating and running registry manager job to import the entries from the text file to the new hub");

            // Step 3: Call import using the same blob to create all devices.
            // Loads devices.txt and adds the devices to the destination hub.
            using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(destHubConnectionString);
            JobProperties importJob = await registryManager.ImportDevicesAsync(containerUri, containerUri).ConfigureAwait(false);

            // Wait until job is finished
            while (true)
            {
                importJob = await registryManager.GetJobAsync(importJob.JobId).ConfigureAwait(false);

                Console.WriteLine($"Import job status is {importJob.Status}");
                if (importJob.Status == JobStatus.Completed ||
                    importJob.Status == JobStatus.Failed ||
                    importJob.Status == JobStatus.Cancelled)
                {
                    // Job has finished executing
                    break;
                }

                await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
            }
        }
Example #18
0
 public async Task DeleteFile(string targetContainer, string filename)
 {
     CloudBlobContainer container = StorageClient.GetContainerReference(targetContainer);
     CloudBlockBlob     blockBlob = container.GetBlockBlobReference(filename);
     await blockBlob.DeleteIfExistsAsync();
 }
 public async Task DeleteBlobAsync(CloudBlockBlob blockBlob)
 {
     await blockBlob.DeleteIfExistsAsync();
 }
        private async Task <ActionResponse> UploadBlockAsync(string fileName, byte[] fileBytes, string partitionName, Dictionary <string, string> metaData, string data, DocumentContentType documentContentType)
        {
            CloudBlockBlob blockBlob = null;
            var            blobUri   = string.Empty;
            var            blockName = GetBlockName(partitionName, fileName);

            var result = Policy
                         .Handle <Exception>()
                         .WaitAndRetryAsync(
                _maxRetryValueForBlobAction,
                retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                (exception, timeSpan, retryCount, context) =>
            {
                _logger.LogError($"Retey {retryCount} after {timeSpan.TotalSeconds} of Blob {exception.Message}");
            }
                );

            await result.ExecuteAsync(
                async() =>
            {
                if (blockBlob == null)
                {
                    blockBlob = await GetBlockBlobAsync(_containerName, blockName);
                }

                if (blockBlob != null)
                {
                    await blockBlob.DeleteIfExistsAsync();
                    switch (documentContentType)
                    {
                    case DocumentContentType.Byte:
                        await blockBlob.UploadFromByteArrayAsync(fileBytes, 0, fileBytes.Length);
                        break;

                    case DocumentContentType.Text:
                        await blockBlob.UploadTextAsync(data);
                        break;

                    default:
                        break;
                    }

                    if (metaData != null)
                    {
                        foreach (var keyValue in metaData)
                        {
                            if (blockBlob.Metadata.ContainsKey(keyValue.Key))
                            {
                                blockBlob.Metadata.Remove(keyValue);
                            }

                            blockBlob.Metadata.Add(keyValue);
                        }

                        await blockBlob.SetMetadataAsync();
                    }

                    blobUri = blockBlob.Uri.ToString();
                }
            });

            return(!string.IsNullOrEmpty(blobUri) ? ActionResponse.UploadSuccessResponse(fileName, blobUri) : ActionResponse.FailResponse(fileName, new ErrorCodes {
                Message = Constants.SomethingWentWrongMessage, Code = Constants.SomethingWentWrongCode
            }));
        }
        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>A Task object.</returns>
        private static async Task BasicStorageBlockBlobOperationsWithAccountSASAsync()
        {
            const string ImageToUpload = "HelloWorld.png";
            string       containerName = ContainerPrefix + Guid.NewGuid();

            // Get an account SAS token.
            string sasToken = GetAccountSASToken();

            // Use the account SAS token to create authentication credentials.
            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();

            // Get the URI for the container.
            Uri containerUri = GetContainerUri(containerName);

            // Get a reference to a container using the URI and the SAS token.
            CloudBlobContainer container = new CloudBlobContainer(containerUri, accountSAS);

            try
            {
                // Create a container for organizing blobs within the storage account.
                Console.WriteLine("1. Creating Container using Account SAS");

                await container.CreateIfNotExistsAsync();
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.ToString());
                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;
            }

            try
            {
                // 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);

                // List all the blobs in the container
                Console.WriteLine("3. List Blobs in Container");
                BlobContinuationToken token = null;
                do
                {
                    BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(token);

                    token = resultSegment.ContinuationToken;
                    foreach (IListBlobItem blob in resultSegment.Results)
                    {
                        // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
                        Console.WriteLine("{0} (type: {1}", blob.Uri, blob.GetType());
                    }
                }while (token != null);

                // 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);

                // Delete the blob and its snapshots.
                Console.WriteLine("6. Delete block Blob and all of its snapshots");
                await blockBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
            finally
            {
                // Clean up after the demo.
                // Note that it is not necessary to delete all of the blobs in the container first; they will be deleted
                // with the container.
                Console.WriteLine("7. Delete Container");
                await container.DeleteIfExistsAsync();
            }
        }
Example #22
0
        private static async Task SearchBlobsAsync(CloudBlobContainer container)
        {
            if (await container.ExistsAsync())
            {
                WriteLine($"Enter the path to search, leave blank to search the entire '{container.Name}' container:");
                WriteLineWithGreenColor(true);
                WriteLine($"Ex: blobreceipts/hostId/namespace.functionName.Run");
                WriteLineWithGreenColor(false);
                var prefix = @ReadLine();

                WriteLine($"Enter the start date by counting the number of days from today on which the search should start.");
                WriteLineWithGreenColor(true);
                WriteLine($"Ex: 1 is {DateTime.Now.AddDays(-1)} (yesterday) and 5 is {DateTime.Now.AddDays(-5)} (5 days ago)");
                WriteLineWithGreenColor(false);
                int startDate = (ToInt32(ReadLine()) * -1);

                WriteLine($"Enter the end date by counting the number of days from today on which the search should end.");
                WriteLineWithGreenColor(true);
                WriteLine($"Enter 0 for now {DateTime.Now}");
                WriteLineWithGreenColor(false);
                int endDate = (ToInt32(ReadLine()) * -1);
                if (endDate == 0)
                {
                    endDate = 1;               //Seems this logic didn't work when endDate was 0, but nothing can already exist which is added tomorrow...
                }
                if (startDate > endDate)
                {
                    WriteLine($"Start date {DateTime.Now.AddDays(startDate)} " +
                              $"cannot come before end date {DateTime.Now.AddDays(endDate)}, start over.");
                    return;
                }
                WriteLineWithGreenColor(true);
                WriteLine($"Searching '{container.Name} -> {prefix}' from {DateTime.Now.AddDays(startDate)} " +
                          $"to {DateTime.Now.AddDays(endDate)}");
                WriteLineWithGreenColor(false);

                try
                {
                    int maxResults = 500;
                    BlobContinuationToken       continuationToken = null;
                    CloudBlob                   blob;
                    IEnumerable <IListBlobItem> blobList;

                    do
                    {
                        BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(prefix,
                                                                                                  true, BlobListingDetails.Metadata, maxResults, continuationToken, null, null);

                        blobList = resultSegment.Results.OfType <CloudBlob>()
                                   .Where(b => b.Properties.Created >= DateTime.Today.AddDays(startDate) &&
                                          b.Properties.Created <= DateTime.Today.AddDays(endDate))
                                   .Select(b => b);

                        foreach (var blobItem in blobList)
                        {
                            blob = (CloudBlob)blobItem;
                            await blob.FetchAttributesAsync();

                            WriteLine($"Blob name: {blob.Name} - last modified on {blob.Properties.LastModified}");
                        }
                        continuationToken = resultSegment.ContinuationToken;
                    } while (continuationToken != null);

                    if (blobList.Count() > 0)
                    {
                        WriteLine("Would you like to remove/reprocess a blob? Y/N ");
                        var delete = ReadLine();
                        while (delete == "Y")
                        {
                            //should repopulate blobList and check there are blobs to delete
                            WriteLine("Enter the path and blob name you would like to remove/reprocess: ");
                            WriteLineWithGreenColor(true);
                            WriteLine($"Ex: {((CloudBlob)blobList.First()).Name}");
                            WriteLineWithGreenColor(false);
                            var path = ReadLine();

                            CloudBlockBlob blockBlob = container.GetBlockBlobReference(path);
                            await blockBlob.DeleteIfExistsAsync();

                            WriteLine($"Deleted {path} from {container.Name}");

                            WriteLine("Would you like to remove/reprocess another blob? Y/N ");
                            delete = ReadLine();
                        }
                    }
                }
                catch (StorageException e)
                {
                    WriteLine(e.Message);
                    ReadLine();
                }

                if (container.Name.ToLower() != "azure-webjobs-hosts")
                {
                    WriteLineWithYellowColor(true);
                    WriteLine($"NOTE: you searched '{container.Name} -> {prefix}'.  You need to search in the " +
                              "azure-webjobs-hosts container if you want to reprocess a blob.");
                    WriteLineWithYellowColor(false);
                }
            }
            else
            {
                WriteLine($"Blob container '{container.Name}' doesn't exist.  Please start over.");
            }
        }
        public static async System.Threading.Tasks.Task <ActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "indexDeleteAll")] HttpRequest req,
            [CosmosDB(ConnectionStringSetting = "CosmosDB")] DocumentClient client, ILogger log)
        {
            SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName: "jfk-search-service-qymjpzort5hho", credentials: new SearchCredentials("023DB82430FFA416AD39EEF8A6FDFF2A"));
            ISearchIndexClient  indexClient   = serviceClient.Indexes.GetClient("jfkindex");
            DocumentSearchResult <Microsoft.Azure.Search.Models.Document> searchResult;

            try
            {
                searchResult = indexClient.Documents.Search <Microsoft.Azure.Search.Models.Document>(string.Empty);
            }
            catch (Exception e)
            {
                throw new Exception("Error al recorrer index", e);
            }
            List <string> azureDocsToDelete =
                searchResult
                .Results
                .Select(r => r.Document["id"].ToString())
                .ToList();

            try
            {
                var batch  = IndexBatch.Delete("id", azureDocsToDelete);
                var result = indexClient.Documents.Index(batch);
            }
            catch (IndexBatchException ex)
            {
                throw new Exception($"error al eliminar documentos : {string.Join(", ", ex.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key))}");
            }
            Database db = client.CreateDatabaseQuery()
                          .Where(d => d.Id == "taskDatabase")
                          .AsEnumerable()
                          .SingleOrDefault();
            DocumentCollection coll = client.CreateDocumentCollectionQuery(db.SelfLink)
                                      .Where(c => c.Id == "TaskCollection")
                                      .ToList()
                                      .SingleOrDefault();
            var docs = client.CreateDocumentQuery(coll.DocumentsLink);

            foreach (var doc in docs)
            {
                await client.DeleteDocumentAsync(doc.SelfLink);
            }
            DocumentCollection coll2 = client.CreateDocumentCollectionQuery(db.SelfLink)
                                       .Where(c => c.Id == "recorrido")
                                       .ToList()
                                       .SingleOrDefault();
            var docs2 = client.CreateDocumentQuery(coll.DocumentsLink);

            foreach (var doc in docs)
            {
                await client.DeleteDocumentAsync(doc.SelfLink);
            }
            StorageCredentials storageCredentials = new StorageCredentials("jfkstorageqymjpzort5hho",
                                                                           "CamEKgqVaylmQta0aUTqN8vUy/xvUewVYZOrBvF1mh85zlgtj3fm7YheYRgoB6paMp+VcFUpTRIlow2VHlyCww==");
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, useHttps: true);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container      = blobClient.GetContainerReference("datum");
            List <string>       blobs          = new List <string>();
            BlobResultSegment   resultSegment  = await container.ListBlobsSegmentedAsync(null);

            foreach (IListBlobItem item in resultSegment.Results)
            {
                CloudBlockBlob blob = (CloudBlockBlob)item;
                blobs.Add(blob.Name);
            }
            foreach (var file in blobs)
            {
                CloudBlockBlob blob = container.GetBlockBlobReference(file);
                await blob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);
            }
            return((ActionResult) new OkObjectResult($" function ejecutado"));
        }
        private async Task <bool> DeleteFileFromStorageAsync(string fileName, CloudBlockBlob blockBlob)
        {
            bool isSuccess = await blockBlob.DeleteIfExistsAsync();

            return(await Task.FromResult(isSuccess));
        }
Example #25
0
        public async Task PublishAsync(DataQueryOptions filter, string fileName, CancellationTokenSource cancellationTokenSource)
        {
            try
            {
                // Get container reference
                CloudBlobContainer container = _blobClient.GetContainerReference(CsvContainerName);
                await container.CreateIfNotExistsAsync(cancellationTokenSource.Token);

                // Delete old if exists
                CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
                await blob.DeleteIfExistsAsync(cancellationTokenSource.Token);

                // Create temp file and serialize data to it
                using (var stream = new MemoryStream())
                {
                    // Prepare data filter
                    int limit = filter.Take.HasValue && filter.Take.Value > 0 ? filter.Take.Value : Int32.MaxValue;

                    if (filter.Take.HasValue && filter.Take.Value > 0)
                    {
                        // limit specified
                        if (filter.Take.Value > CsvBatchSize)
                        {
                            // splitting data into batches
                            filter.Take = CsvBatchSize;
                        }
                    }
                    else
                    {
                        filter.Take = CsvBatchSize;
                    }

                    filter.Skip = filter.Skip.HasValue && filter.Skip.Value > 0 ? filter.Skip.Value : 0;

                    // Adding utf-8 BOM. Details http://stackoverflow.com/questions/4414088/how-to-getbytes-in-c-sharp-with-utf8-encoding-with-bom/4414118#4414118
                    byte[] bom = Encoding.UTF8.GetPreamble();
                    await stream.WriteAsync(bom, 0, bom.Length, cancellationTokenSource.Token);

                    // Batch serialization
                    var serializationTokenSource = new CancellationTokenSource();
                    while (!cancellationTokenSource.IsCancellationRequested && !serializationTokenSource.IsCancellationRequested)
                    {
                        // loading batch
                        object data = await OnDataRequest(filter, serializationTokenSource);

                        // serializing batch
                        await _mediaTypeFormatter.WriteToStreamAsync(data.GetType(), data, stream, null, null, cancellationTokenSource.Token);

                        if (filter.Skip + filter.Take == limit)
                        {
                            // all loaded
                            break;
                        }

                        // next batch
                        filter.Skip += CsvBatchSize;
                        if (filter.Skip + CsvBatchSize >= limit)
                        {
                            filter.Take = limit - filter.Skip;
                        }
                    }

                    // Upload result to blob
                    stream.Position = 0;
                    await blob.UploadFromStreamAsync(stream, cancellationTokenSource.Token);
                }

                // Set content type
                await blob.FetchAttributesAsync(cancellationTokenSource.Token);

                blob.Properties.ContentType = "text/csv";
                await blob.SetPropertiesAsync(cancellationTokenSource.Token);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to publish csv file: {0}", e);
            }
        }
Example #26
0
 public async Task DeleteBlobAsync(string keyNotHashed, CloudBlobContainer container)
 {
     CloudBlockBlob blob = container.GetBlockBlobReference(KeyGeneratorHelper.GenerateHashValue(keyNotHashed));
     await blob.DeleteIfExistsAsync();
 }
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            //Get our object for this position
            var item = items[position];
            //Try to reuse convertView if it's not  null, otherwise inflate it from our item layout
            // This gives us some performance gains by not always inflating a new view
            // This will sound familiar to MonoTouch developers with UITableViewCell.DequeueReusableCell()
            var view = (convertView ??
                        context.LayoutInflater.Inflate(
                            Resource.Layout.AzureImageList,
                            parent,
                            false)) as LinearLayout;
            //Find references to each subview in the list item's view
            var imageItem  = view.FindViewById(Resource.Id.azureimageItem) as ImageView;
            var textTop    = view.FindViewById(Resource.Id.azuretextTop) as TextView;
            var textBottom = view.FindViewById(Resource.Id.azuretextBottom) as TextView;
            //var mycheckbox = view.FindViewById(Resource.Id.azureCheckboxItem) as CheckBox;
            var viewazureimagebutton   = view.FindViewById(Resource.Id.viewazureimagebutton) as Button;
            var deleteazureimagebutton = view.FindViewById(Resource.Id.deleteazureimagebutton) as Button;

            deleteazureimagebutton.Click += async delegate
            {
                /*
                 * var myazureimagenamestrtmp = item.Description;
                 * var myazureimagenamearr = myazureimagenamestrtmp.IndexOf(".jpg");
                 * var cutimgstr = myazureimagenamestrtmp.Substring(0, myazureimagenamearr);
                 * var imgstrarr = cutimgstr.Split(new Char[] { '/' }).ToList();
                 * var countidximgname = imgstrarr.Count - 1;
                 * var myrealimgname = imgstrarr[countidximgname] + ".jpg";
                 * var deleteazureurl = "http://93.115.97.151/azureservice/list.php?containerid=115708452302383620142&action=delete&filename=" + myrealimgname;
                 * //var deleteazureurl = "http://93.118.34.239:8888/deleteblob/115708452302383620142/" + myrealimgname;
                 * var browser = new WebView(Application.Context);
                 * browser.LoadUrl(deleteazureurl);
                 *
                 * Toast.MakeText(Application.Context, "File has been delete", ToastLength.Long).Show();
                 * */

                try
                {
                    var myazureimageurldown = new Uri(item.Description);
                    var cloudBlob           = new CloudBlockBlob(myazureimageurldown);

                    await cloudBlob.DeleteIfExistsAsync();

                    Toast.MakeText(Application.Context, "File has been delete", ToastLength.Long).Show();
                }
                catch { }


                /*
                 *  var myazureimagenamestrtmp = item.Description;
                 *  var myazureimagenamearr = myazureimagenamestrtmp.IndexOf(".jpg");
                 *  var cutimgstr = myazureimagenamestrtmp.Substring(0, myazureimagenamearr);
                 *  var imgstrarr = cutimgstr.Split(new Char[] { '/' }).ToList();
                 *  var countidximgname = imgstrarr.Count - 1;
                 *  var myrealimgname = imgstrarr[countidximgname] + ".jpg";
                 *  var deleteazureurl = "http://93.115.97.151/azureservice/list.php?containerid=115708452302383620142&action=delete&filename=" + myrealimgname;
                 *  Uri deleteazureuri = new Uri(deleteazureurl);
                 *  var client = new RestClient(deleteazureurl);
                 *  var request = new RestRequest();
                 *  client.ExecuteAsync(request, response =>
                 *  {
                 *      //Console.WriteLine(response.Content);
                 *      Toast.MakeText(Application.Context, response.Content, ToastLength.Short).Show();
                 *  });
                 *  //IRestResponse response = client.Execute(request);
                 *
                 *  //var myjsonstr = response.Content;
                 */
            };
            //save value to sqlite when checkbox click

            /*
             * mycheckbox.Text = item.Description;
             * mycheckbox.Click += (o, e) =>
             * {
             *  if (mycheckbox.Checked)
             *  {
             *
             *      var mycbitemid = mycheckbox.Text;
             *      Toast.MakeText(Application.Context, mycbitemid, ToastLength.Short).Show();
             *
             *      ISQLiteConnection connactionc = null;
             *      ISQLiteConnectionFactory factoryc = new MvxDroidSQLiteConnectionFactory();
             *
             *      var sqlitedir = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto");
             *      string filename = sqlitedir.Path + "/mysqliteaction.db";
             *      //Toast.MakeText(Application.Context, filename, ToastLength.Long).Show();
             *
             *      connactionc = factoryc.Create(filename);
             *      connactionc.CreateTable<MyCheckbox>();
             *      connactionc.Insert(new MyCheckbox() { Name = mycbitemid });
             *      connactionc.Close();
             *
             *      //var mycbitemid = mycheckbox.Text;
             *      //myCollection.Add(mycbitemid);
             *      //Toast.MakeText(Application.Context, myCollection.Count.ToString(), ToastLength.Short).Show();
             *  }
             *
             * };
             * */
            //End save value
            viewazureimagebutton.Click += async delegate
            {
                var myazureimageurldown = new Uri(item.Description);
                var cloudBlob           = new CloudBlockBlob(myazureimageurldown);

                MemoryStream imageStream            = new MemoryStream();
                var          myazureimagenamestrtmp = item.Description;
                var          myazureimagenamearr    = myazureimagenamestrtmp.IndexOf(".jpg");
                var          cutimgstr       = myazureimagenamestrtmp.Substring(0, myazureimagenamearr);
                var          imgstrarr       = cutimgstr.Split(new Char[] { '/' }).ToList();
                var          countidximgname = imgstrarr.Count - 1;
                var          myrealimgname   = imgstrarr[countidximgname] + ".jpg";
                await cloudBlob.DownloadToStreamAsync(imageStream);

                var    myfiledir  = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "");
                string myfilename = myfiledir.Path + "/" + myrealimgname;


                /*
                 * using (FileStream file = new FileStream(myfilename, FileMode.Create, System.IO.FileAccess.Write))
                 * {
                 *  imageStream.CopyTo(file);
                 *  imageStream.Close();
                 * }
                 * */
                using (var fileStream = File.Create(myfilename))
                {
                    imageStream.Seek(0, SeekOrigin.Begin);
                    imageStream.CopyTo(fileStream);
                    Toast.MakeText(Application.Context, "Saved file into:" + myfilename, ToastLength.Short).Show();
                }
            };

            //Assign this item's values to the various subviews
            //Bitmap bitmap;
            //bitmap = BitmapFactory.DecodeFile(item.Image);

            // First we get the the dimensions of the file on disk

            //var myuri = getImageUri(item.Description);

            //Uri contentUri = Uri.FromFile(myimgfile);
            //Koush.UrlImageViewHelper.SetUrlDrawable(imageItem, item.Image);
            //Koush.UrlImageViewHelper.SetUrlDrawable(imageItem, "https://s.gravatar.com/avatar/7d1f32b86a6076963e7beab73dddf7ca?s=300");
            Koush.UrlImageViewHelper.SetUrlDrawable(imageItem, item.Description);
            Uri contentUri = new Uri(item.Description);


            textTop.SetText(item.Name, TextView.BufferType.Normal);
            //textBottom.SetText(item.Description, TextView.BufferType.Normal);
            textBottom.SetText(item.Description, TextView.BufferType.Normal);
            //textBottom.SetText("", TextView.BufferType.Normal);
            //Finally return the view
            return(view);
        }
Example #28
0
 public void DeleteIfExists()
 {
     _blob.DeleteIfExistsAsync().Wait();
 }
Example #29
0
        //---------------------------------------------------------------------------------------
        // This shows how to copy devices from one IoT Hub to another.
        // First, export the list from the Source hut to devices.txt (ExportDevices).
        // Next, read in that file. Each row is a serialized object;
        //   read them into the generic list serializedDevices.
        // Delete the devices.txt in blob storage, because you're going to recreate it.
        // For each serializedDevice, deserialize it, set ImportMode to CREATE,
        //   reserialize it, and write it to a StringBuilder. The ImportMode field is what
        //   tells the job framework to add each device.
        // Write the new StringBuilder to the block blob.
        //   This essentially replaces the list with a list of devices that have ImportJob = Delete.
        // Call ImportDevicesAsync, which will read in the list in devices.txt, then add each one
        //   because it doesn't already exist. If it already exists, it will write an entry to
        //   the import error log and not add the new one.
        public static async Task CopyAllDevicesToNewHub(string sourceHubConnectionString,
                                                        string destHubConnectionString, CloudBlobContainer cloudBlobContainer,
                                                        string containerURI, string deviceListFile)
        {
            // Read the devices from the hub and write them to devices.txt in blob storage.
            await ExportDevices(containerURI, sourceHubConnectionString);

            // Read devices.txt which contains serialized objects.
            // Write each line to the serializedDevices list. (List<string>).
            CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference(deviceListFile);

            // Get the URI for the blob.
            string blobURI = blockBlob.Uri.ToString();

            // Instantiate the generic list.
            var serializedDevices = new List <string>();

            // Read the blob file of devices, import each row into serializedDevices.
            using (var streamReader =
                       new StreamReader(await blockBlob.OpenReadAsync(AccessCondition.GenerateIfExistsCondition(),
                                                                      null, null), Encoding.UTF8))
            {
                while (streamReader.Peek() != -1)
                {
                    string line = await streamReader.ReadLineAsync();

                    serializedDevices.Add(line);
                }
            }

            // Delete the blob containing the list of devices,
            //   because you're going to recreate it.
            CloudBlockBlob blobToDelete = cloudBlobContainer.GetBlockBlobReference("devices.txt");

            // Step 1: Update each device's ImportMode to be Create
            StringBuilder sb = new StringBuilder();

            serializedDevices.ForEach(serializedDevice =>
            {
                // Deserialize back to an ExportImportDevice.
                var device = JsonConvert.DeserializeObject <ExportImportDevice>(serializedDevice);

                // Update the property.
                device.ImportMode = ImportMode.Create;

                // Re-serialize the object now that you're updated the property.
                sb.AppendLine(JsonConvert.SerializeObject(device));
            });

            // Step 2: Delete the blob if it already exists, then write the list in memory to the blob.
            await blobToDelete.DeleteIfExistsAsync();

            using (CloudBlobStream stream = await blobToDelete.OpenWriteAsync())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
                for (var i = 0; i < bytes.Length; i += 500)
                {
                    int length = Math.Min(bytes.Length - i, 500);
                    await stream.WriteAsync(bytes, i, length);
                }
            }

            // Step 3: Call import using the same blob to create all devices.
            // Loads devices.txt and adds the devices to the destination hub.
            RegistryManager registryManager =
                RegistryManager.CreateFromConnectionString(destHubConnectionString);
            JobProperties importJob =
                await registryManager.ImportDevicesAsync(containerURI, containerURI);

            // Wait until job is finished
            while (true)
            {
                importJob = await registryManager.GetJobAsync(importJob.JobId);

                if (importJob.Status == JobStatus.Completed ||
                    importJob.Status == JobStatus.Failed ||
                    importJob.Status == JobStatus.Cancelled)
                {
                    // Job has finished executing
                    break;
                }

                await Task.Delay(TimeSpan.FromSeconds(5));
            }
        }
Example #30
0
        public async Task <bool> Delete(string path)
        {
            CloudBlockBlob blockBlob = _container.GetBlockBlobReference(path);

            return(await blockBlob.DeleteIfExistsAsync());
        }