public static CloudBlob GetCloudBlob(this CloudStorageAccount cloudStorageAccount, string containerName, string blobName) { Guard.Null(cloudStorageAccount, nameof(cloudStorageAccount)); Guard.NullOrEmpty(containerName, nameof(containerName)); Guard.NullOrEmpty(blobName, nameof(blobName)); try { var blobClient = cloudStorageAccount?.CreateCloudBlobClient(); var blobContainer = blobClient?.GetContainerReference(containerName); return(blobContainer?.GetBlobReference(blobName)); } catch (StorageException) { return(default);
public async Task <UploadFileServiceModel> UploadToBlobAsync(string tenantId, string filename, Stream stream = null) { CloudStorageAccount storageAccount = null; CloudBlobContainer cloudBlobContainer = null; UploadFileServiceModel uploadFileModel = new UploadFileServiceModel(); string url = string.Empty; string md5CheckSum = string.Empty; string sha1CheckSum = string.Empty; string storageConnectionString = this.config.Global.StorageAccountConnectionString; string duration = this.config.Global.PackageSharedAccessExpiryTime; if (string.IsNullOrEmpty(tenantId)) { this.logger.LogError(new Exception("Tenant ID is blank, cannot create container without tenandId."), "Tenant ID is blank, cannot create container without tenandId."); return(null); } if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount)) { try { // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account. CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); // Create a container cloudBlobContainer = cloudBlobClient.GetContainerReference($"{tenantId}-{SoftwarePackageStore}"); // Create the container if it does not already exist await cloudBlobContainer.CreateIfNotExistsAsync(); // Get a reference to the blob address, then upload the file to the blob. CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(filename); if (stream != null) { await cloudBlockBlob.UploadFromStreamAsync(stream); md5CheckSum = cloudBlockBlob.Properties.ContentMD5; using (var sha = SHA1.Create()) { stream.Position = 0; // Update position for computing hash var hash = sha.ComputeHash(stream); cloudBlockBlob.Metadata["SHA1"] = sha1CheckSum = Convert.ToBase64String(hash); } } else { this.logger.LogError(new Exception("Empty stream object in the UploadToBlob method."), "Empty stream object in the UploadToBlob method."); return(null); } url = Convert.ToString(this.GetBlobSasUri(cloudBlobClient, cloudBlobContainer.Name, filename, duration)); uploadFileModel.CheckSum = new CheckSumModel(); uploadFileModel.SoftwarePackageURL = url; uploadFileModel.CheckSum.MD5 = md5CheckSum; uploadFileModel.CheckSum.SHA1 = sha1CheckSum; return(uploadFileModel); } catch (StorageException ex) { this.logger.LogError(new Exception($"Exception in the UploadToBlob method- Message: {ex.Message} : Stack Trace - {ex.StackTrace.ToString()}"), $"Exception in the UploadToBlob method- Message: {ex.Message} : Stack Trace - {ex.StackTrace.ToString()}"); return(null); } } else { this.logger.LogError(new Exception("Error parsing CloudStorageAccount in UploadToBlob method"), "Error parsing CloudStorageAccount in UploadToBlob method"); return(null); } }
public static void Run([TimerTrigger("0 */1 * * * *", RunOnStartup = false)]TimerInfo myTimer, ILogger log) #endif { Engine engine = new Engine(log); try { string responseString = ""; CloudStorageAccount storageAccount = engine.StorageAccount; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); //*****TODO***** externalize labeled data container name. CloudBlobContainer labeledDataContainer = blobClient.GetContainerReference("labeleddata"); Model model = new Model(log); // with a container load training tags if (labeledDataContainer.ListBlobs(null, false) != null) { //*****TODO***** Where should search be initialized? Azure search does not offer CLI calls to configure all of search so it needs to be initialized befor it can be used as a service. Look at putting it in engine. Recognize this is not the same thing as migrating search to a non-static mode and then newing it up. //Search.InitializeSearch(); // Create Reference to Azure Storage Account var storageHelper = new Storage.Helper(); var StorageAccount = storageHelper.GetStorageAccount(); var BlobClient = StorageAccount.CreateCloudBlobClient(); var LabeledDataContainer = BlobClient.GetContainerReference("labeleddata"); var Client = new HttpClient(); var Response = new HttpResponseMessage(); var ResponseString = ""; //Add full set set of labeled training data to the model //*****TODO***** add logic to only add incremental labeled data to model string addLabeledDataResult = model.AddLabeledData(); //Train model using latest labeled training data. string trainingResultsString = model.Train(); string TrainingDataUrl; foreach (var item in LabeledDataContainer.ListBlobs(null, false)) { if (item.GetType() == typeof(CloudBlockBlob)) { var dataCloudBlockBlob = (CloudBlockBlob)item; TrainingDataUrl = dataCloudBlockBlob.Uri.ToString(); var BindingHash = dataCloudBlockBlob.Properties.ContentMD5.ToString(); if (BindingHash == null) { //compute the file hash as this will be added to the meta data to allow for file version validation var BlobMd5 = dataCloudBlockBlob.ToString().CalculateMD5Hash(); if (BlobMd5 == null) { log.LogInformation("\nWarning: Blob Hash calculation failed and will not be included in file information blob, continuing operation."); } else { dataCloudBlockBlob.Properties.ContentMD5 = BlobMd5; } } //trim the 2 "equals" off the trailing end of the hash or the http send will fail either using the client or raw http calls. BindingHash = BindingHash.Substring(0, BindingHash.Length - 2); //Get the content from the bound JSON file and instanciate a JsonBlob class then retrieve the labels collection from the Json to add to the image. var json = storageHelper.DownloadBlobAsString(StorageAccount, "json", BindingHash); var model = json.ToStorageModel(); var labels = Uri.EscapeDataString(JsonConvert.SerializeObject(model.Labels)); //construct and call model URL then fetch response // the model always sends the label set in the message body with the name LabelsJson. If your model needs other values in the URL then use //{ {environment variable name}}. // So the example load labels function in the sameple model package would look like this: // https://branddetectionapp.azurewebsites.net/api/loadimagetags/?projectID={{ProjectID}} // The orchestration engine appends the labels json file to the message body. // http://localhost:7071/api/LoadImageTags/?projectID=8d9d12d1-5d5c-4893-b915-4b5b3201f78e&labelsJson={%22Labels%22:[%22Hemlock%22,%22Japanese%20Cherry%22]} var AddLabeledDataUrl = model.Search.Url; AddLabeledDataUrl = ConstructModelRequestUrl(AddLabeledDataUrl, labels, log); Response = Client.GetAsync(AddLabeledDataUrl).Result; ResponseString = Response.Content.ReadAsStringAsync().Result; if (string.IsNullOrEmpty(ResponseString)) throw new MissingRequiredObjectException($"\nresponseString not generated from URL: {AddLabeledDataUrl}"); //the code below is for passing labels and conent as http content and not on the URL string. //Format the Data Labels content //HttpRequestMessage Request = new HttpRequestMessage(HttpMethod.Post, new Uri(AddLabeledDataUrl)); //HttpContent DataLabelsStringContent = new StringContent(trainingDataLabels, Encoding.UTF8, "application/x-www-form-urlencoded"); //MultipartFormDataContent LabeledDataContent = new MultipartFormDataContent(); //LabeledDataContent.Add(DataLabelsStringContent, "LabeledData"); //Format the data cotent //*****TODO***** move to an async architecture //*****TODO***** need to decide if there is value in sending the data as a binary stream in the post or if requireing the model data scienctist to accept URLs is sufficient. If accessing the data blob with a SAS url requires Azure classes then create a configuration to pass the data as a stream in the post. If there is then this should be a configurable option. //MemoryStream dataBlobMemStream = new MemoryStream(); //dataBlob.DownloadToStream(dataBlobMemStream); //HttpContent LabeledDataHttpContent = new StreamContent(dataBlobMemStream); //LabeledDataContent.Add(LabeledDataContent, "LabeledData"); //Make the http call and get a response //string AddLabelingTagsEndpoint = Engine.GetEnvironmentVariable("LabeledDataServiceEndpoint", log); //if (string.IsNullOrEmpty(AddLabelingTagsEndpoint)) throw (new EnvironmentVariableNotSetException("LabeledDataServiceEndpoint environment variable not set")); //string ResponseString = Helper.GetEvaluationResponseString(AddLabelingTagsEndpoint, LabeledDataContent, log); //if (string.IsNullOrEmpty(ResponseString)) throw (new MissingRequiredObject("\nresponseString not generated from URL: " + AddLabelingTagsEndpoint)); log.LogInformation($"Successfully added blob: {dataCloudBlockBlob.Name} with labels: {JsonConvert.SerializeObject(model.Labels)}"); } } //Invoke the train model web service call var trainModelUrl = Engine.GetEnvironmentVariable("TrainModelServiceEndpoint", log); if (string.IsNullOrEmpty(trainModelUrl)) throw new EnvironmentVariableNotSetException("TrainModelServiceEndpoint environment variable not set"); Client = new HttpClient(); Response = Client.GetAsync(trainModelUrl).Result; ResponseString = Response.Content.ReadAsStringAsync().Result; if (string.IsNullOrEmpty(ResponseString)) throw new MissingRequiredObjectException($"\nresponseString not generated from URL: {trainModelUrl}"); log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); } catch (Exception e) { log.LogInformation("\nError processing training timer: ", e.Message); } }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); //Set up link to blob storage for stored images string storageConnectionString = "<YOUR STORAGE CONNECTION STRING HERE>"; CloudStorageAccount blobAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = blobAccount.CreateCloudBlobClient(); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); if (!string.IsNullOrEmpty(requestBody)) { dynamic data = JsonConvert.DeserializeObject(requestBody); string sourceName = data.sourceName; string sourceContainer = data.sourceContainer; string destinationName = data.destinationName; string destinationContainer = data.destinationContainer; string probability = data.probability; int i = 0; if (!string.IsNullOrEmpty(sourceName)) { //Get reference to specific car's container from Car Reg (converts to lower case as container names must be lower case) CloudBlobContainer blobContainer = blobClient.GetContainerReference(sourceContainer.ToLower()); //Get reference to image block blob image from ImageFileName parameter the user passed in (images must be in jpg format in the blob service for this to work) CloudBlockBlob cloudBlockBlob = blobContainer.GetBlockBlobReference(sourceName.ToLower()); //Download the image to a stream using (var inputStream = await cloudBlockBlob.OpenReadAsync().ConfigureAwait(false)) { using (var image = Image.Load(inputStream)) { //For each boundingbox, blur the rectangle foreach (var bb in data.boundingBox) { i += 1; int left = bb.left; int top = bb.top; int width = bb.width; int height = bb.height; image.Mutate(x => x.GaussianBlur(20, new Rectangle(left, top, width, height))); log.LogInformation("Object " + i + " blurred."); } log.LogInformation("Finished image."); //Upload the stream to Blob Storage byte[] arr; using (MemoryStream streamOut = new MemoryStream()) { image.SaveAsJpeg(streamOut); arr = streamOut.GetBuffer(); CloudBlobContainer cloudBlobContainerDest = blobClient.GetContainerReference(destinationContainer.ToLower()); await cloudBlobContainerDest.CreateIfNotExistsAsync(); CloudBlockBlob cloudBlockBlobDest = cloudBlobContainerDest.GetBlockBlobReference(destinationName); streamOut.Seek(0, SeekOrigin.Begin); //Task.WaitAll(cloudBlockBlobDest.UploadFromStreamAsync(streamOut)); await cloudBlockBlobDest.UploadFromStreamAsync(streamOut); } //Create the Http response message with the blurred image HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); return((ActionResult) new OkObjectResult("Uploaded to Blob storage")); } } } else { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest); return(new BadRequestObjectResult("Please pass a valid source url in the request body.")); } } else { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest); return(new BadRequestObjectResult("Please pass a valid request body.")); } }
private async void btnUpload_Click(object sender, RoutedEventArgs e) { try { btnUpload.IsEnabled = false; btnUpload.Content = "Uploading......"; string fileName = ""; bool imageExist = false; string fileAddress = ""; Random r = new Random(); if (!storageFile.Equals(null)) { imageExist = true; // Source: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-javascript-backend-windows-universal-dotnet-upload-data-blob-storage/#test // Part one: upload images to database // Create the connectionstring String StorageConnectionString = "DefaultEndpointsProtocol=https;AccountName=uonlife;AccountKey=LzU9gRoJgvtKtY7rIPE3w1Z7Toc39AfcBO+Y+Q4ZCYoZmXd2KTgpZ5muya6JkxaZRtNAo3ib3FTpw7gAncpOPA=="; // Retrieve storage account from connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageConnectionString); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve a reference to a container. (pictures) CloudBlobContainer container = blobClient.GetContainerReference("images"); await container.CreateIfNotExistsAsync(); string sFileName = img.Source.ToString(); fileName = tbxName.Text.Trim() + r.Next(10000000, 99999999).ToString() + ".jpg"; CloudBlockBlob blobFromSASCredential = container.GetBlockBlobReference(fileName); await blobFromSASCredential.UploadFromFileAsync(storageFile); } // Step two: store data into table if (imageExist == true) { fileAddress = "https://uonlife.blob.core.windows.net/images/" + fileName; } Society society = new Society { societyName = tbxName.Text, clubwebsite = tbxWebsite.Text, places = tbxPlaces.Text, description = tbxDescription.Text, contact = tbxContact.Text, imageAddress = fileAddress, publisher = GlobalVariable.loginUser }; await App.mobileService.GetTable <Society>().InsertAsync(society); MessageDialog msgbox = new MessageDialog("Upload success"); await msgbox.ShowAsync(); Frame.Navigate(typeof(MainPage)); } catch (Exception ex) { MessageDialog msgbox = new MessageDialog("Error: " + ex.Message); await msgbox.ShowAsync(); btnUpload.IsEnabled = true; btnUpload.Content = "Upload"; } }
public string CreateStorageAccount( string resourceGroupName, string storageAccountName, string label, string description, string location, string containerName, out string storageAccountSuffix ) { var stoInput = new StorageAccountCreateParameters { Location = location, Kind = Kind.Storage, Sku = new Microsoft.Azure.Management.Storage.Models.Sku { Name = SkuName.StandardGRS } }; // Retrieve the storage account storageManagementClient.StorageAccounts.Create( resourceGroupName, storageAccountName, stoInput ); // Retrieve the storage account primary access key var accessKey = storageManagementClient.StorageAccounts.ListKeys( resourceGroupName, storageAccountName ).Keys[0].Value; ThrowIfTrue( string.IsNullOrEmpty(accessKey), "storageManagementClient.StorageAccounts.ListKeys returned null." ); // Create container // Since this is a data-plane client and not an ARM client it's harder to inject // HttpMockServer into it to record/playback, but that's fine because we don't need // any of the response data to continue with the test. if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Record) { CloudStorageAccount storageAccountClient = new CloudStorageAccount( new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials( storageAccountName, accessKey), useHttps: true); CloudBlobClient blobClient = storageAccountClient.CreateCloudBlobClient(); CloudBlobContainer containerReference = blobClient.GetContainerReference(containerName); containerReference.CreateIfNotExistsAsync().GetAwaiter().GetResult(); } // Set the storage account suffix var getResponse = storageManagementClient.StorageAccounts.GetProperties( resourceGroupName, storageAccountName ); storageAccountSuffix = getResponse.PrimaryEndpoints.Blob.ToString(); storageAccountSuffix = storageAccountSuffix.Replace("https://", "").TrimEnd('/'); storageAccountSuffix = storageAccountSuffix.Replace(storageAccountName, "").TrimStart('.'); // Remove the opening "blob." if it exists. storageAccountSuffix = storageAccountSuffix.Replace("blob.", ""); return(accessKey); }
/// <summary> /// Provides an asynchronous version of the Main method, allowing for the awaiting of async method calls within. /// </summary> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> private static async Task MainAsync() { Console.WriteLine("Sample start: {0}", DateTime.Now); Console.WriteLine(); Stopwatch timer = new Stopwatch(); timer.Start(); // Construct the Storage account connection string string storageConnectionString = String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", StorageAccountName, StorageAccountKey); // Retrieve the storage account CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); // Create the blob client, for use in obtaining references to blob storage containers CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Use the blob client to create the containers in blob storage const string inputContainerName = "input"; const string outputContainerName = "output"; await CreateContainerIfNotExistAsync(blobClient, inputContainerName); await CreateContainerIfNotExistAsync(blobClient, outputContainerName); // RESOURCE FILE SETUP // Input files: Specify the location of the data files that the tasks process, and // put them in a List collection. Make sure you have copied the data files to: // \<solutiondir>\InputFiles. string inputPath = Path.Combine(Environment.CurrentDirectory, "InputFiles"); List<string> inputFilePaths = new List<string>(Directory.GetFileSystemEntries(inputPath, "*.mp4", SearchOption.TopDirectoryOnly)); // Upload data files. // Upload the data files using UploadResourceFilesToContainer(). This data will be // processed by each of the tasks that are executed on the compute nodes within the pool. List<ResourceFile> inputFiles = await UploadFilesToContainerAsync(blobClient, inputContainerName, inputFilePaths); // Obtain a shared access signature that provides write access to the output container to which // the tasks will upload their output. string outputContainerSasUrl = GetContainerSasUrl(blobClient, outputContainerName, SharedAccessBlobPermissions.Write); // CREATE BATCH CLIENT / CREATE POOL / CREATE JOB / ADD TASKS // Create a Batch client and authenticate with shared key credentials. // The Batch client allows the app to interact with the Batch service. BatchSharedKeyCredentials sharedKeyCredentials = new BatchSharedKeyCredentials(BatchAccountUrl, BatchAccountName, BatchAccountKey); using (BatchClient batchClient = BatchClient.Open(sharedKeyCredentials)) { // Create the Batch pool, which contains the compute nodes that execute the tasks. await CreatePoolIfNotExistAsync(batchClient, PoolId); // Create the job that runs the tasks. await CreateJobAsync(batchClient, JobId, PoolId); // Create a collection of tasks and add them to the Batch job. // Provide a shared access signature for the tasks so that they can upload their output // to the Storage container. await AddTasksAsync(batchClient, JobId, inputFiles, outputContainerSasUrl); // Monitor task success or failure, specifying a maximum amount of time to wait for // the tasks to complete. await MonitorTasks(batchClient, JobId, TimeSpan.FromMinutes(30)); // Delete input container in storage Console.WriteLine("Deleting container [{0}]...", inputContainerName); CloudBlobContainer container = blobClient.GetContainerReference(inputContainerName); await container.DeleteIfExistsAsync(); // Print out timing info timer.Stop(); Console.WriteLine(); Console.WriteLine("Sample end: {0}", DateTime.Now); Console.WriteLine("Elapsed time: {0}", timer.Elapsed); // Clean up Batch resources (if the user so chooses) Console.WriteLine(); Console.Write("Delete job? [yes] no: "); string response = Console.ReadLine().ToLower(); if (response != "n" && response != "no") { await batchClient.JobOperations.DeleteJobAsync(JobId); } Console.Write("Delete pool? [yes] no: "); response = Console.ReadLine().ToLower(); if (response != "n" && response != "no") { await batchClient.PoolOperations.DeletePoolAsync(PoolId); } } }
public MagazineCoverContext(CloudStorageAccount account) { _cloudBlobContainer = account.CreateCloudBlobClient().GetContainerReference(MagazineCoverContext.MagazineCoverContainer); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("A new Ticket request has been submitted"); var formData = await req.ReadFormAsync(); var email = new Email { Dkim = formData["dkim"], To = formData["to"], Html = formData["html"], From = formData["from"], Text = formData["text"], SenderIp = formData["sender_ip"], Envelope = formData["envelope"], Attachments = int.Parse(formData["attachments"]), Subject = formData["subject"], Charsets = formData["charsets"], Spf = formData["spf"], }; String strorageconn = System.Environment.GetEnvironmentVariable("storageAccount"); CloudStorageAccount storageacc = CloudStorageAccount.Parse(strorageconn); CloudBlobClient blobClient = storageacc.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(System.Environment.GetEnvironmentVariable("containerName")); await container.CreateIfNotExistsAsync(); var uris = new List <Uri>(); foreach (var file in req.Form.Files) { CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName); using (var filestream = file.OpenReadStream()) { await blockBlob.UploadFromStreamAsync(filestream); } uris.Add(blockBlob.Uri); } string accountSid = System.Environment.GetEnvironmentVariable("accountSid"); string authToken = System.Environment.GetEnvironmentVariable("accountSecret"); TwilioClient.Init(accountSid, authToken); var message = MessageResource.Create( from: new Twilio.Types.PhoneNumber($"whatsapp:{System.Environment.GetEnvironmentVariable("fromNumber")}"), body: email.Text, to: new Twilio.Types.PhoneNumber($"whatsapp:{email.Subject}"), mediaUrl: uris ); return(new OkObjectResult($"Ticket delivered!")); }
/// <summary> /// FileIndex for keeping order of events... /// </summary> /// <param name="storage">Connection</param> /// <param name="container">Azure blob container</param> /// <param name="directoryNaming">directoryNaming if you wanna write to a sub path</param> /// <param name="leaseTime">You can acquire leases for 15s up to 60s or you can acquire a lease for an infinite time period.</param> public FolderIndexVersion(CloudStorageAccount storage, string container, string filename, TimeSpan?leaseTime = null) { this.leaseTime = leaseTime ?? TimeSpan.FromSeconds(30); //You can acquire leases for 15s up to 60s or you can acquire a lease for an infinite time period. this.blob = storage.CreateCloudBlobClient().GetContainerReference(container).GetAppendBlobReference(filename); }
public StorageHelper(string containerName) { _storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["storageConnectionString"]); _blobClient = _storageAccount.CreateCloudBlobClient(); _blobContainer = _blobClient.GetContainerReference(containerName); }
protected void btnFullPost_Click(object sender, EventArgs e) { string folderPath = Server.MapPath("~/Files/"); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } long filesize = FileUpload1.FileBytes.Length; if (filesize / (1024 * 1024) <= 1) { error.Visible = false; FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName)); Image1.ImageUrl = "~/Files/" + Path.GetFileName(FileUpload1.FileName); } else { error.Visible = true; } StorageCredentials storageCredentials = new StorageCredentials("cvtierone", ""); CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("cv-bw-input-images"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(FileUpload1.FileName); string BWImagePath = Server.MapPath(Image1.ImageUrl); blockBlob.UploadFromFile(Server.MapPath(Image1.ImageUrl)); System.Threading.Thread.Sleep(5000); CloudBlobContainer containerRGB = blobClient.GetContainerReference("cv-bw-2-color"); string FileName = FileUpload1.FileName.Split('.')[0]; string FileEnding = FileUpload1.FileName.Split('.')[1]; string RGBImageName = FileName + "_RGB." + FileEnding; CloudBlockBlob blob = containerRGB.GetBlockBlobReference(RGBImageName); string localRGBImagePath = Server.MapPath("~/RGBImages/") + RGBImageName; System.IO.FileMode mode = FileMode.Create; int i = 0; string errorout = ""; while (i < 30) { try { blob.DownloadToFile(localRGBImagePath, mode); } catch (Exception exception) { errorout = exception.ToString(); } if (!(File.Exists(localRGBImagePath))) { i++; System.Threading.Thread.Sleep(1000); } else { i = 32; } } ; Image2.ImageUrl = "~/RGBImages/" + RGBImageName; imgtable.Style.Add(HtmlTextWriterStyle.Display, "normal"); }
private static CloudBlobClient GetCloudBlobClient(CloudStorageAccount account) { return(account.CreateCloudBlobClient()); }
public void CloudStorageAccountClientMethods() { CloudStorageAccount account = new CloudStorageAccount(TestBase.StorageCredentials, false); CloudBlobClient blob = account.CreateCloudBlobClient(); CloudQueueClient queue = account.CreateCloudQueueClient(); CloudTableClient table = account.CreateCloudTableClient(); // check endpoints Assert.AreEqual(account.BlobEndpoint, blob.BaseUri, "Blob endpoint doesn't match account"); Assert.AreEqual(account.QueueEndpoint, queue.BaseUri, "Queue endpoint doesn't match account"); Assert.AreEqual(account.TableEndpoint, table.BaseUri, "Table endpoint doesn't match account"); // check storage uris Assert.AreEqual(account.BlobStorageUri, blob.StorageUri, "Blob endpoint doesn't match account"); Assert.AreEqual(account.QueueStorageUri, queue.StorageUri, "Queue endpoint doesn't match account"); Assert.AreEqual(account.TableStorageUri, table.StorageUri, "Table endpoint doesn't match account"); // check creds Assert.AreEqual(account.Credentials, blob.Credentials, "Blob creds don't match account"); Assert.AreEqual(account.Credentials, queue.Credentials, "Queue creds don't match account"); Assert.AreEqual(account.Credentials, table.Credentials, "Table creds don't match account"); }
public void CloudStorageAccountWithStorageUri() { StorageUri blobEndpoint = new StorageUri( new Uri("http://" + AccountName + BlobService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + BlobService + EndpointSuffix)); StorageUri queueEndpoint = new StorageUri( new Uri("http://" + AccountName + QueueService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + QueueService + EndpointSuffix)); StorageUri tableEndpoint = new StorageUri( new Uri("http://" + AccountName + TableService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + TableService + EndpointSuffix)); StorageUri fileEndpoint = new StorageUri( new Uri("http://" + AccountName + FileService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + FileService + EndpointSuffix)); #if WINDOWS_RT || ASPNET_K CloudStorageAccount account = CloudStorageAccount.Create(new StorageCredentials(), blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint); #else CloudStorageAccount account = new CloudStorageAccount(new StorageCredentials(), blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint); #endif Assert.IsTrue(blobEndpoint.Equals(account.BlobStorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.QueueStorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.TableStorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.FileStorageUri)); account = new CloudStorageAccount(new StorageCredentials(AccountName, TestBase.StorageCredentials.ExportBase64EncodedKey()), false); Assert.IsTrue(blobEndpoint.Equals(account.BlobStorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.QueueStorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.TableStorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.FileStorageUri)); account = CloudStorageAccount.Parse(string.Format("DefaultEndpointsProtocol=http;AccountName={0};AccountKey=", AccountName)); Assert.IsTrue(blobEndpoint.Equals(account.BlobStorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.QueueStorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.TableStorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.FileStorageUri)); Assert.IsTrue(blobEndpoint.Equals(account.CreateCloudBlobClient().StorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.CreateCloudQueueClient().StorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.CreateCloudTableClient().StorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.CreateCloudFileClient().StorageUri)); Assert.IsTrue(blobEndpoint.PrimaryUri.Equals(account.BlobEndpoint)); Assert.IsTrue(queueEndpoint.PrimaryUri.Equals(account.QueueEndpoint)); Assert.IsTrue(tableEndpoint.PrimaryUri.Equals(account.TableEndpoint)); Assert.IsTrue(fileEndpoint.PrimaryUri.Equals(account.FileEndpoint)); }
/// <summary> /// Get a service channel object using specified storage account /// </summary> /// <param name="account">Cloud storage account object</param> /// <returns>IStorageBlobManagement channel object</returns> protected IStorageBlobManagement CreateChannel(CloudStorageAccount account) { return(new StorageBlobManagement(account.CreateCloudBlobClient())); }
/// <summary> /// Private constructor. /// </summary> /// <param name="account">The current account</param> /// <param name="containerName">The container name</param> private BlobStorageSession(CloudStorageAccount account, string containerName) { client = account.CreateCloudBlobClient(); container = client.GetContainerReference(containerName); }
static void Main(string[] args) { string storageConnectionString = $"DefaultEndpointsProtocol=https;AccountName={StorageAccountName};AccountKey={StorageAccountKey}"; // Retrieve the storage account CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); // Create the blob client CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); const string inputContainerName = "batchinput"; List <string> inputFilePaths = new List <string> { "taskdata0.txt", "taskdata1.txt", "taskdata2.txt" }; // Upload the input files to blob storage List <ResourceFile> inputFiles = new List <ResourceFile>(); foreach (string filePath in inputFilePaths) { inputFiles.Add(UploadFileToContainer(blobClient, inputContainerName, filePath)); } // Get a SAS Url for the output container const string outputContainerName = "batchoutput"; string outputContainerSasUrl = GetOutputContainerSasUrl(blobClient, outputContainerName); // Create the virtual machine image reference ImageReference imageReference = new ImageReference( publisher: "MicrosoftWindowsServer", offer: "WindowsServer", sku: "2016-datacenter-smalldisk", version: "latest"); // Create the virtual machine configuration for the pool VirtualMachineConfiguration virtualMachineConfiguration = new VirtualMachineConfiguration( imageReference: imageReference, nodeAgentSkuId: "batch.node.windows amd64"); BatchSharedKeyCredentials cred = new BatchSharedKeyCredentials(BatchAccountUrl, BatchAccountName, BatchAccountKey); using (BatchClient batchClient = BatchClient.Open(cred)) { Console.WriteLine("Creating pool [{0}]...", PoolId); try { CloudPool pool = batchClient.PoolOperations.CreatePool( poolId: PoolId, targetDedicatedComputeNodes: PoolNodeCount, virtualMachineSize: PoolVMSize, virtualMachineConfiguration: virtualMachineConfiguration); // Specify the application packages for the tasks pool.ApplicationPackageReferences = new List <ApplicationPackageReference> { new ApplicationPackageReference { ApplicationId = "ReadWriteFile", Version = "1" } }; pool.Commit(); } catch (BatchException be) { // Accept the specific error code PoolExists as that is expected if the pool already exists if (be.RequestInformation?.BatchError?.Code == BatchErrorCodeStrings.PoolExists) { Console.WriteLine("The pool {0} already existed when we tried to create it", PoolId); } else { throw; // Any other exception is unexpected } } Console.WriteLine("Creating job [{0}]...", JobId); try { CloudJob job = batchClient.JobOperations.CreateJob(); job.Id = JobId; job.PoolInformation = new PoolInformation { PoolId = PoolId }; job.Commit(); } catch (BatchException be) { // Accept the specific error code JobExists as that is expected if the job already exists if (be.RequestInformation?.BatchError?.Code == BatchErrorCodeStrings.JobExists) { Console.WriteLine("The job {0} already existed when we tried to create it", JobId); } else { throw; // Any other exception is unexpected } } // Create a collection to hold the tasks that we'll be adding to the job Console.WriteLine("Adding {0} tasks to job [{1}]...", inputFiles.Count, JobId); List <CloudTask> tasks = new List <CloudTask>(); // Create each of the tasks to process one of the input files. for (int i = 0; i < inputFiles.Count; i++) { string taskId = String.Format("Task{0}", i); string inputFilename = inputFiles[i].FilePath; string outputFileName = string.Format("out{0}", inputFilename); string taskCommandLine = string.Format("cmd /c %AZ_BATCH_APP_PACKAGE_READWRITEFILE%\\ReadWriteFile.exe {0} {1}", inputFilename, outputFileName); CloudTask task = new CloudTask(taskId, taskCommandLine); // Set the resource files and output files for the task task.ResourceFiles = new List <ResourceFile> { inputFiles[i] }; task.OutputFiles = new List <OutputFile> { new OutputFile( filePattern: outputFileName, destination: new OutputFileDestination(new OutputFileBlobContainerDestination(containerUrl: outputContainerSasUrl, path: outputFileName)), uploadOptions: new OutputFileUploadOptions(OutputFileUploadCondition.TaskCompletion)) }; tasks.Add(task); } // Add all tasks to the job. batchClient.JobOperations.AddTask(JobId, tasks); // Monitor task success/failure, specifying a maximum amount of time to wait for the tasks to complete. TimeSpan timeout = TimeSpan.FromMinutes(30); Console.WriteLine("Monitoring all tasks for 'Completed' state, timeout in {0}...", timeout); IEnumerable <CloudTask> addedTasks = batchClient.JobOperations.ListTasks(JobId); batchClient.Utilities.CreateTaskStateMonitor().WaitAll(addedTasks, TaskState.Completed, timeout); Console.WriteLine("All tasks reached state Completed."); // Print task output Console.WriteLine(); Console.WriteLine("Printing task output..."); IEnumerable <CloudTask> completedtasks = batchClient.JobOperations.ListTasks(JobId); foreach (CloudTask task in completedtasks) { string nodeId = String.Format(task.ComputeNodeInformation.ComputeNodeId); Console.WriteLine("Task: {0}", task.Id); Console.WriteLine("Node: {0}", nodeId); Console.WriteLine("Standard out:"); Console.WriteLine(task.GetNodeFile(Constants.StandardOutFileName).ReadAsString()); } // Clean up Batch resources (if the user so chooses) Console.WriteLine(); Console.Write("Delete job? [yes] no: "); string response = Console.ReadLine().ToLower(); if (response != "n" && response != "no") { batchClient.JobOperations.DeleteJob(JobId); } Console.Write("Delete pool? [yes] no: "); response = Console.ReadLine().ToLower(); if (response != "n" && response != "no") { batchClient.PoolOperations.DeletePool(PoolId); } } }
/// <summary> /// Creates a blob connection and blob client using user secrets. /// </summary> /// <param name="configuration"></param> public Blob(IConfiguration configuration) { CloudStorageAccount = CloudStorageAccount.Parse(configuration["ConnectionStrings:BlobConnectionString"]); CloudBlobClient = CloudStorageAccount.CreateCloudBlobClient(); }
/// <summary> /// Ingest all Mezzamine files to Asset /// </summary> private void IngestAssets() { IAccessPolicy writePolicy = MediaContext.AccessPolicies.Create("writePolicy_" + currentAsset.Name, TimeSpan.FromMinutes(120), AccessPermissions.Write); ILocator destinationLocator = MediaContext.Locators.CreateLocator(LocatorType.Sas, currentAsset, writePolicy); //Asset Storage CloudStorageAccount assetStorageCount = CloudStorageAccount.Parse(myRequest.MediaStorageConn); CloudBlobClient assetClient = assetStorageCount.CreateCloudBlobClient(); CloudBlobContainer assetContainer = assetClient.GetContainerReference(currentAsset.Uri.Segments[1]); //Mezzamine Storage CloudStorageAccount MezzamineStorageCount = CloudStorageAccount.Parse(myRequest.ButlerRequest.StorageConnectionString); CloudBlobClient MezzamineClient = MezzamineStorageCount.CreateCloudBlobClient(); CloudBlobContainer MezzamineContainer = MezzamineClient.GetContainerReference(myRequest.ButlerRequest.WorkflowName); //Filter Ingest only MP4 foreach (string urlMezzamineFile in myRequest.ButlerRequest.MezzanineFiles.Where(mf => mf.ToLower().EndsWith(".mp4"))) { Uri xFile = new Uri(urlMezzamineFile); int segmentIndex = xFile.Segments.Count() - 1; //Asset BLOB Xfile string AssetBlobName = Uri.UnescapeDataString(xFile.Segments[segmentIndex]); CloudBlockBlob assetBlob = assetContainer.GetBlockBlobReference(AssetBlobName); assetContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob } ); //Mezzamine BLOB Xfile string MezzamineBlobName = ""; for (int i = 2; i <= segmentIndex; i++) { MezzamineBlobName += xFile.Segments[i]; } MezzamineBlobName = Uri.UnescapeDataString(MezzamineBlobName); CloudBlockBlob MezzamineBlob = MezzamineContainer.GetBlockBlobReference(MezzamineBlobName); var sas = MezzamineContainer.GetSharedAccessSignature(new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15), SharedAccessExpiryTime = DateTime.UtcNow.AddDays(7), Permissions = SharedAccessBlobPermissions.Read, }); //USE decode URL for spetial characters var srcBlockBlobSasUri = string.Format("{0}{1}", Uri.UnescapeDataString(MezzamineBlob.Uri.AbsoluteUri), sas); assetBlob.StartCopy(new Uri(srcBlockBlobSasUri)); Trace.TraceInformation("{0} in process {1} processId {2} Start copy MezzamineFile {3}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, MezzamineBlobName); CloudBlockBlob blobStatusCheck; blobStatusCheck = (CloudBlockBlob)assetContainer.GetBlobReferenceFromServer(AssetBlobName); while (blobStatusCheck.CopyState.Status == CopyStatus.Pending) { Task.Delay(TimeSpan.FromSeconds(10d)).Wait(); Trace.TraceInformation("{0} in process {1} processId {2} copying MezzamineFile {3} status {4}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, MezzamineBlobName, blobStatusCheck.CopyState.Status); blobStatusCheck = (CloudBlockBlob)assetContainer.GetBlobReferenceFromServer(AssetBlobName); } assetBlob.FetchAttributes(); //Add the xFile to Asset var assetFile = currentAsset.AssetFiles.Create(AssetBlobName); MezzamineBlob.FetchAttributes(); assetFile.ContentFileSize = MezzamineBlob.Properties.Length; assetFile.Update(); Trace.TraceInformation("{0} in process {1} processId {2} finish MezzamineFile {3}", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId, MezzamineBlobName); } destinationLocator.Delete(); writePolicy.Delete(); currentAsset.Update(); }
public AzureFileStorage() { _storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["azure-storage"].ConnectionString); _blobClient = _storageAccount.CreateCloudBlobClient(); }
public JsonStoreClient(CloudStorageAccount account) { this.blobClient = account.CreateCloudBlobClient(); }
public static CloudBlobContainer InitContainer(string accountName, string accountKey, string containerName, bool isPublic, int threadCount = -1, long uploadThreshold = -1, ILogger logger = null) { if (logger != null) { logger.Log("Initializing container " + accountName + " " + containerName + " account key " + ((accountKey == null) ? "null" : "non-null")); } if (!AzureConsts.ValidContainerName(containerName)) { throw new BlobException(BlobException.Status.InvalidContainerName); } // Create the blob client. CloudBlobClient blobClient; if (accountKey == null) { Uri baseUri = new Uri("http://" + accountName + Utils.BlobHostSuffix); blobClient = new CloudBlobClient(baseUri); } else { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(GetConnectionString(accountName, accountKey)); blobClient = storageAccount.CreateCloudBlobClient(); } blobClient.DefaultRequestOptions.MaximumExecutionTime = AzureConsts.DefaultMaximumExecutionTime; if (threadCount > 0) { blobClient.DefaultRequestOptions.ParallelOperationThreadCount = threadCount; } if (uploadThreshold > 0) { blobClient.DefaultRequestOptions.SingleBlobUploadThresholdInBytes = uploadThreshold; } // Retrieve a reference to a container. CloudBlobContainer container = blobClient.GetContainerReference(containerName); // Create the container if it doesn't already exist. bool created = container.CreateIfNotExists(); if (created) { if (logger != null) { logger.Log("Created container"); } // Set permissions on the container. BlobContainerPermissions containerPermissions = new BlobContainerPermissions(); containerPermissions.PublicAccess = (isPublic) ? BlobContainerPublicAccessType.Blob : BlobContainerPublicAccessType.Off; container.SetPermissions(containerPermissions); if (logger != null) { logger.Log("Set container permissions"); } } return(container); }
private static void GetNetworkSecurityGroupEvents(DateTime logStart, DateTime logEnd) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(BlobStorageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); Console.WriteLine($"Getting reference to container {EventContainerName}"); CloudBlobContainer container = blobClient.GetContainerReference(EventContainerName); StorageURL storageUrl = new StorageURL(container.Uri, SubscriptionID, ResrouceGroupsName, ProviderName, ResrouceTypeName, ResourceType.NETWORKSECURITYGROUPS); List <Log> logs = new List <Log>(); int itemPosition = 0; for (DateTime logTimeStamp = logStart; logTimeStamp <= logEnd; logTimeStamp = logTimeStamp.AddHours(1)) { Console.WriteLine(logTimeStamp); Uri storageBlogUrl = storageUrl.GetURL(logTimeStamp); CloudBlockBlob blockBlob = new CloudBlockBlob(storageBlogUrl, storageAccount.Credentials); MemoryStream memstream = new MemoryStream(); try { blockBlob.DownloadToStream(memstream); memstream.Position = 0; JsonSerializer serializer = new JsonSerializer(); using (StreamReader sr = new StreamReader(memstream)) using (JsonTextReader jsonTextReader = new JsonTextReader(sr)) { LogRecords logRecords = serializer.Deserialize <LogRecords>(jsonTextReader); itemPosition = 0; foreach (Log logItem in logRecords.records) { logs.Add(logItem); itemPosition++; } } } catch (Exception ex) { Console.WriteLine($"{ex.Message} - {storageBlogUrl}"); } } using (System.IO.StreamWriter file = new System.IO.StreamWriter(EventCSVExportNamePath)) { file.WriteLine("time,systemId,resourceId,operationName,properties.vnetResourceGuid,properties.subnetPrefix" + ",properties.macAddress,properties.ruleName,properties.direction,properties.priority" + ",properties.type,properties.conditions.destinationPortRange,properties.conditions.sourcePortRange" + ",properties.conditions.sourceIP,properties.conditions.destinationIP,properties.conditions.protocols"); foreach (Log log in logs) { file.WriteLine($"{DateTime.Parse(log.time).ToUniversalTime()}, {log.systemId}, {log.resourceId}, {log.operationName}" + $", {log.properties.vnetResourceGuid}, {log.properties.subnetPrefix}, {log.properties.macAddress}" + $", {log.properties.ruleName}, {log.properties.direction}, {log.properties.priority}, {log.properties.type}" + $", {log.properties.conditions.destinationPortRange}, {log.properties.conditions.sourcePortRange}" + $", {log.properties.conditions.sourceIP?.Replace(',', ';')}, {log.properties.conditions.destinationIP?.Replace(',', ';')}" + $", {(string.IsNullOrWhiteSpace(log.properties.conditions.protocols) ? "*" : log.properties.conditions.protocols?.Replace(',', ';'))}"); } } }
public static async void Run( [TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ExecutionContext context, ILogger log) { config = Helpers.GetConfig(context); WarningThreshold = Int32.Parse(config["WarningThreshold"]); CriticalThreshold = Int32.Parse(config["CriticalThreshold"]); DownThreshold = Int32.Parse(config["DownThreshold"]); var gameBlob = Helpers.GetBlob(context, log, config["CloudStorageContainer"], config["CloudStorageBlobFile"]); var gameList = Helpers.GetBlobAsList(gameBlob, log); CloudStorageAccount storageAccount = Helpers.GetCloudStorageAccount(context); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(config["CloudStorageBlobFile"]); var blobs = container.ListBlobs(prefix: "loginEvents", useFlatBlobListing: true).OfType <CloudBlockBlob>().ToList(); if (blobs.Count == 0) { foreach (Game savedGame in gameList) { UpdateStatus(savedGame.LoginAlert, new AverageLoginEvent() { TitleId = savedGame.TitleId }, savedGame.Title, log); UpdateAverageStatus(savedGame.LoginAlert, new AverageLoginEvent() { TitleId = savedGame.TitleId }, savedGame.Title, log); } } else { foreach (var blobEvent in blobs) { List <AverageLoginEvent> currentList = BlobHelpers <AverageLoginEvent> .GetBlobContentLineByLine(blobEvent, log); foreach (Game savedGame in gameList) { log.LogInformation($"{DateTime.UtcNow} - Processing game {savedGame.Title}"); if (currentList.Exists(requestGame => requestGame.TitleId == savedGame.TitleId)) { AverageLoginEvent currentStatus = currentList.Find(x => x.TitleId == savedGame.TitleId); log.LogInformation($"{DateTime.UtcNow} - Game {savedGame.Title} has recorded events. Updating persisted status."); UpdateStatus(savedGame.LoginAlert, currentStatus, savedGame.Title, log); UpdateAverageStatus(savedGame.LoginAlert, currentStatus, savedGame.Title, log); } else { log.LogInformation($"{DateTime.UtcNow} - Game {savedGame.Title} does not have any recorded events. Updating persisted status."); UpdateStatus(savedGame.LoginAlert, new AverageLoginEvent() { TitleId = savedGame.TitleId }, savedGame.Title, log); UpdateAverageStatus(savedGame.LoginAlert, new AverageLoginEvent() { TitleId = savedGame.TitleId }, savedGame.Title, log); } } blobEvent.Delete(); } } await Helpers.UploadGame(gameBlob, gameList, log); }
/// <summary> /// 初始化儲存體物件的動作 /// </summary> public AzureStorage() { storageAccount = CloudStorageAccount.Parse(strConn); blobClient = storageAccount.CreateCloudBlobClient(); }
private void CreateMediaAsset(CloudFile model) { string mediaAccountName = ConfigurationManager.AppSettings["MediaAccountName"]; string mediaAccountKey = ConfigurationManager.AppSettings["MediaAccountKey"]; string storageAccountName = ConfigurationManager.AppSettings["StorageAccountName"]; string storageAccountKey = ConfigurationManager.AppSettings["StorageAccountKey"]; CloudMediaContext context = new CloudMediaContext(mediaAccountName, mediaAccountKey); var storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, storageAccountKey), true); var cloudBlobClient = storageAccount.CreateCloudBlobClient(); var mediaBlobContainer = cloudBlobClient.GetContainerReference(cloudBlobClient.BaseUri + "temporary-media"); mediaBlobContainer.CreateIfNotExists(); // Create a new asset. IAsset asset = context.Assets.Create("NewAsset_" + Guid.NewGuid(), AssetCreationOptions.None); IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy", TimeSpan.FromMinutes(120), AccessPermissions.Write); ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy); // Get the asset container URI and copy blobs from mediaContainer to assetContainer. Uri uploadUri = new Uri(destinationLocator.Path); string assetContainerName = uploadUri.Segments[1]; CloudBlobContainer assetContainer = cloudBlobClient.GetContainerReference(assetContainerName); string fileName = HttpUtility.UrlDecode(Path.GetFileName(model.BlockBlob.Uri.AbsoluteUri)); var sourceCloudBlob = mediaBlobContainer.GetBlockBlobReference(fileName); sourceCloudBlob.FetchAttributes(); if (sourceCloudBlob.Properties.Length > 0) { IAssetFile assetFile = asset.AssetFiles.Create(fileName); var destinationBlob = assetContainer.GetBlockBlobReference(fileName); destinationBlob.DeleteIfExists(); destinationBlob.StartCopyFromBlob(sourceCloudBlob); destinationBlob.FetchAttributes(); if (sourceCloudBlob.Properties.Length != destinationBlob.Properties.Length) { model.UploadStatusMessage += "Failed to copy as Media Asset!"; } } destinationLocator.Delete(); writePolicy.Delete(); // Refresh the asset. asset = context.Assets.Where(a => a.Id == asset.Id).FirstOrDefault(); var ismAssetFiles = asset.AssetFiles.ToList(). Where(f => f.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase)) .ToArray(); if (ismAssetFiles.Count() != 1) { throw new ArgumentException("The asset should have only one, .ism file"); } ismAssetFiles.First().IsPrimary = true; ismAssetFiles.First().Update(); //model.UploadStatusMessage += " Created Media Asset '" + asset.Name + "' successfully."; model.AssetId = asset.Id; }
static void RawFileMovetoEncrypt() { PGPLib pgp = new PGPLib(); bool asciiArmor = false; bool withIntegrityCheck = false; string sourcePath = @"C:\DATA FILES\Raw Data Files\"; string targetPath = @"C:\DATA FILES\Encrypted Data Files\"; string fileName = ""; int fileSize; string sourceFile = System.IO.Path.Combine(sourcePath, fileName); string destFile = System.IO.Path.Combine(targetPath, fileName); if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = System.IO.Path.GetFileName(s); pgp.EncryptFile(sourcePath + fileName, @"C:\DATA FILES\publickey.asc", targetPath + fileName, asciiArmor, withIntegrityCheck); // destFile = System.IO.Path.Combine(targetPath, fileName); // System.IO.File.Copy(s, destFile, true); } } CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); //encryptedtgblfiles CloudBlobContainer container = blobClient.GetContainerReference("encryptedtgblfiles"); if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { fileName = System.IO.Path.GetFileName(s); CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); fileSize = fileName.Length; // Create or overwrite the "myblob" blob with contents from a local file. using (var fileStream = System.IO.File.OpenRead(targetPath + fileName)) { blockBlob.UploadFromStream(fileStream); } // To move a file or folder to a new location: // logger(fileName, "Uploaded",fileSize); // To move an entire directory. To programmatically modify or combine // path strings, use the System.IO.Path class. //System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private"); } } }
public static async Task <IActionResult> GetResizedImage( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "images-fullres/{filename}")] HttpRequest req, [Blob("images-fullres/{filename}", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream inputStream, [Blob("images-misc/watermark.png", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream watermarkStream, string filename, ILogger log) { // Wywala 500 Internal Server Error zanim w ogóle to sprawdzi. //if (req.Query["w"] != int.Parse(req.Query["w"]).ToString() || req.Query["h"] != int.Parse(req.Query["h"]).ToString() || int.Parse(req.Query["w"]) <= 0 || int.Parse(req.Query["h"]) <= 0) //{ // return new BadRequestObjectResult("Invalid non-optional parameters."); //} // Pobieramy parametry z GETa do zmiennych. string width = req.Query["w"]; // Szerokość obrazka. string height = req.Query["h"]; // Wysokość obrazka. string center = req.Query["c"]; // Czy obrazek ma być wycentrowany, przyjmuje 'yes'. string watermark = req.Query["wm"]; // Czy obrazek ma mieć watermark, przyjmuje 'logo'. int imgWidth = (int.Parse(width) > 5000 ? 5000 : int.Parse(width)); int imgHeight = (int.Parse(height) > 5000 ? 5000 : int.Parse(height)); // To zwraca IActionResult w przypadku OkObjectResult. string returnMessage = ""; // Łączenie się ze Azure Storage Account i tworzenie klienta. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageAccountConnectionString); CloudBlobClient client = storageAccount.CreateCloudBlobClient(); // Pobieranie bloba wejściowego tylko w celu sprawdzenia, czy istnieje. Image.Load(inputStream) nie działa. CloudBlobContainer inputContainer = client.GetContainerReference("images-fullres"); CloudBlobDirectory inputDirectory = inputContainer.GetDirectoryReference(""); CloudBlockBlob inputBlob = inputDirectory.GetBlockBlobReference($"{filename}"); //Stream inputStream = new MemoryStream(); //await inputBlob.DownloadToStreamAsync(inputStream); // Alternatywne pobieranie watermarka. Image.Load(watermarkStream) wywala to samo, co w przypadku inputStream. //CloudBlobContainer miscContainer = client.GetContainerReference("images-misc"); //CloudBlobDirectory miscDirectory = miscContainer.GetDirectoryReference(""); //CloudBlockBlob watermarkBlob = miscDirectory.GetBlockBlobReference("watermark.png"); //Stream watermarkStream = new MemoryStream(); //await watermarkBlob.DownloadToStreamAsync(watermarkStream); // Pobieranie bloba wyjściowego, do niego zapisujemy gotowy obrazek. CloudBlobContainer outputContainer = client.GetContainerReference("images-thumb"); outputContainer.CreateIfNotExists(); CloudBlobDirectory outputDirectory = outputContainer.GetDirectoryReference($"{imgWidth}/{imgHeight}"); if (center == "yes") { outputDirectory = outputContainer.GetDirectoryReference($"{imgWidth}/{imgHeight}/center"); } CloudBlockBlob outputBlob = outputDirectory.GetBlockBlobReference($"thumb-{filename}"); if (watermark == "logo") { outputBlob = outputDirectory.GetBlockBlobReference($"watermark-thumb-{filename}"); } Stream outputStream = new MemoryStream(); // Jeżeli obrazek do przeskalowania nie istnieje. if (!inputBlob.Exists()) { return(new BadRequestObjectResult("Result:\n" + "The image doesn't exist.")); } // Jeżeli obrazek o podanych wymiarach już istnieje. else if (outputBlob.Exists()) { return(new OkObjectResult($"Result:\n" + $"The image already exists in the given dimensions.\n" + $"Image link:\n" + $"{outputBlob.Uri}")); } // Obrazek do przeskalowania istnieje, ale nie istnieje jego cache. else { using (var image = Image.Load(inputStream)) { var imageResult = image; // Jeżeli ma być centrowany. if (center == "yes") { try { imageResult.Mutate( x => x.Resize(new ResizeOptions { Mode = ResizeMode.Max, Size = new Size(imgWidth, imgHeight) } ) ); var imageContainer = new Image <Rgba32>(imgWidth, imgHeight, Color.FromRgb(0, 0, 0)); // Jeżeli brakuje mu pikseli w poziomie. if (imageResult.Width < imageContainer.Width) { imageContainer.Mutate(x => x.DrawImage(imageResult, new Point((imageContainer.Width / 2) - (imageResult.Width / 2), 0), 1.0f)); } // Jeżeli brakuje mu pikseli w pionie. if (imageResult.Height < imageContainer.Height) { imageContainer.Mutate(x => x.DrawImage(imageResult, new Point(0, (imageContainer.Height / 2) - (imageResult.Height / 2)), 1.0f)); } imageResult = imageContainer; returnMessage = $"Image resized and centered successfully. Dimensions: {imgWidth}x{imgHeight}"; } catch (Exception e) { Console.WriteLine("{0} Exception caught while centering or resizing image.", e); } } // Jeżeli nie ma być centrowany. else { try { imageResult.Mutate( i => i.Resize(imgWidth, imgHeight) ); returnMessage = $"Image resized successfully. Dimensions: {imgWidth}x{imgHeight}"; } catch (Exception e) { Console.WriteLine("{0} Exception caught while resizing image.", e); } } // Jeżeli ma mieć watermark. if (watermark == "logo") { using (var watermarkImage = Image.Load(watermarkStream)) { try { watermarkImage.Mutate( x => x.Resize(new ResizeOptions { Mode = ResizeMode.Max, Size = new Size(imgWidth / 3, imgHeight) } ) ); imageResult.Mutate(x => x.DrawImage(watermarkImage, new Point(10, 10), 0.5f)); } catch (Exception e) { Console.WriteLine("{0} Exception caught while applying watermark.", e); } } } // Zapisujemy wynik do streama, stream do bloba. try { imageResult.Save(outputStream, new JpegEncoder()); outputStream.Seek(0, SeekOrigin.Begin); await outputBlob.UploadFromStreamAsync(outputStream); } catch (Exception e) { Console.WriteLine("{0} Exception caught while saving image.", e); } } } return(new OkObjectResult($"Result:\n" + $"{returnMessage}\n" + $"Image link:\n" + $"{outputBlob.Uri}")); }
public static async Task Run([QueueTrigger("traces", Connection = "TracesStorageConnectionString")] string traceMessage, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context) { log.LogInformation($"ExchangeMessageTrackingToSplunk function was triggered with the following message: {traceMessage}"); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var traceStorageConnectionString = config["TracesStorageConnectionString"]; if (traceStorageConnectionString == null) { string m = $"{context.InvocationId} - Variable TracesStorageConnectionString is not set in configuration. This function cannot run."; log.LogCritical(m); throw new Exception(m); } log.LogDebug($"{context.InvocationId} - TracesStorageConnectionString: {traceStorageConnectionString.Substring(0, 40)}"); var archiveContainerName = config["TraceArchiveContainerName"]; if (archiveContainerName == null) { log.LogWarning($"{context.InvocationId} - Variable TraceArchiveContainerName is not set in configuration. Using default value: 'trace-archive' "); archiveContainerName = "trace-archive"; } try { log.LogDebug($"{context.InvocationId} - Get hold of archive storage container"); CloudStorageAccount archiveStorageAccount = CloudStorageAccount.Parse(traceStorageConnectionString); CloudBlobClient archiveStorageClient = archiveStorageAccount.CreateCloudBlobClient(); CloudBlobContainer archiveStorageContainer = archiveStorageClient.GetContainerReference(archiveContainerName); if (await archiveStorageContainer.CreateIfNotExistsAsync()) { log.LogInformation(($"{context.InvocationId} - Archive container {archiveContainerName} did not exist and was created sucessfully.")); archiveStorageContainer.Metadata.Add("origin", "Created automatically by ExchangeMessageTrackingToSplunk Function"); await archiveStorageContainer.SetMetadataAsync(); } log.LogInformation($"{context.InvocationId} - Archive container name: {archiveContainerName}"); var blobName = Guid.NewGuid().ToString(); CloudBlockBlob archiveBlob = archiveStorageContainer.GetBlockBlobReference(blobName); log.LogInformation($"{context.InvocationId} -archiveBlob.Uri: {archiveBlob.Uri}"); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(traceMessage))) { await archiveBlob.UploadFromStreamAsync(stream); } log.LogInformation($"{context.InvocationId} -archiveBlob.Uri: {archiveBlob.Uri} was created for message"); } catch (Exception e) { log.LogError($"{context.InvocationId} - Exception {e.Message}"); log.LogError($"{context.InvocationId} - Stacktrace {e.StackTrace}"); if (e.InnerException != null) { log.LogError($"{context.InvocationId} - Inner Exception was {e.InnerException.Message}"); } throw e; } }
public async Task <ActionResult> EditUserProfile(EditProfileViewModel userViewModel, HttpPostedFileBase fileUpload) { try { var fileNames = ""; if (fileUpload != null) { fileNames = DateTime.Now.ToString("yyyymmddMMssfff") + System.IO.Path.GetExtension(fileUpload.FileName); var path = Path.Combine(Server.MapPath("~/Content/"), fileNames); var imagepth = path; fileUpload.SaveAs(imagepth); string connString = ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString; var connStringArray = connString.Split(';'); var dictionary = new Dictionary <string, string>(); foreach (var item in connStringArray) { var itemKeyValue = item.Split('='); dictionary.Add(itemKeyValue[0], itemKeyValue[1]); } string accountname = dictionary["AccountName"]; string accesskeys = dictionary["AccountKey"]; string accesskey = accesskeys + "=="; string BlobKey = WebConfigurationManager.AppSettings["BlobStroageKey"]; var OrigionalImagepath = BlobKey + fileNames; StorageCredentials creden = new StorageCredentials(accountname, accesskey); CloudStorageAccount acc = new CloudStorageAccount(creden, useHttps: true); CloudBlobClient client = acc.CreateCloudBlobClient(); CloudBlobContainer cont = client.GetContainerReference("onboarding"); cont.CreateIfNotExists(); cont.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); CloudBlockBlob cblob = cont.GetBlockBlobReference(fileNames); var LocalImagePath = path.ToString(); using (Stream ddd = System.IO.File.OpenRead(@LocalImagePath)) { cblob.UploadFromStream(ddd); } fileNames = OrigionalImagepath; if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } else { var id = loggedInUser?.Id; fileNames = UserManager.Users.Where(x => x.Id == id).Select(c => c.User_Image).FirstOrDefault(); } AspNetUser editProfileViewModel = new AspNetUser(); ViewBag.Roles = RoleManager.Roles.ToDictionary(m => m.Id, m => m.Name); var user = await UserManager.FindByIdAsync(userViewModel.Id); if (user == null) { return(HttpNotFound()); } var intialsCount = _adminService.GetUsersByInitial(userViewModel.UserInitial, user.Id).Count(); if (intialsCount > 0) { ModelState.AddModelError("UserInitial", $"There is already a User in the system with the same initials. Please enter new Initials using up to three (3) alphanumeric characters."); } if (_adminService.ValidateNPINumber(userViewModel.NPINumber, user.Id)) { ModelState.AddModelError("NPINumber", "There is already a User in the system with the same NPI Number. Please enter a different NPI Number "); } editProfileViewModel.Id = userViewModel.Id; editProfileViewModel.FirstName = userViewModel.FirstName; editProfileViewModel.LastName = userViewModel.LastName; editProfileViewModel.Email = userViewModel.Email; editProfileViewModel.UserName = userViewModel.Username; editProfileViewModel.CreatedBy = userViewModel.CreatedBy; editProfileViewModel.CreatedByName = userViewModel.CreatedByName; editProfileViewModel.EnableFive9 = userViewModel.EnableFive9; editProfileViewModel.MobilePhone = userViewModel.MobilePhone; editProfileViewModel.IsSleep = userViewModel.IsSleep; editProfileViewModel.PhoneNumber = userViewModel.OtherPhone; editProfileViewModel.CreatedDate = userViewModel.CreatedDate; editProfileViewModel.NPINumber = userViewModel.NPINumber; editProfileViewModel.CredentialIndex = userViewModel.CredentialIndex; editProfileViewModel.UserInitial = userViewModel.UserInitial; editProfileViewModel.CaseReviewer = userViewModel.CaseReviewer; editProfileViewModel.IsEEG = userViewModel.IsEEG; editProfileViewModel.IsStrokeAlert = userViewModel.IsStrokeAlert; editProfileViewModel.NHAlert = userViewModel.NHAlert; editProfileViewModel.Address_line1 = userViewModel.Address_line1; editProfileViewModel.Address_line2 = userViewModel.Address_line2; editProfileViewModel.City = userViewModel.City; editProfileViewModel.Zip = userViewModel.Zip; editProfileViewModel.State_key = userViewModel.State_key; editProfileViewModel.PasswordHash = userViewModel.PasswordHash; editProfileViewModel.SecurityStamp = userViewModel.SecurityStamp; editProfileViewModel.IsActive = userViewModel.isActive; editProfileViewModel.IsDisable = userViewModel.isDisable; editProfileViewModel.User_Image = fileNames; editProfileViewModel.ModifiedByName = userViewModel.ModifiedByName; editProfileViewModel.ModifiedBy = userViewModel.ModifiedBy; editProfileViewModel.ModifiedDate = userViewModel.ModifiedDate; editProfileViewModel.RequirePasswordReset = userViewModel.RequirePasswordReset; editProfileViewModel.PasswordExpirationDate = userViewModel.PasswordExpirationDate; editProfileViewModel.TwoFactorEnabled = userViewModel.TwoFactorEnabled; editProfileViewModel.LockoutEndDateUtc = userViewModel.LockoutEndDateUtc; editProfileViewModel.LockoutEnabled = userViewModel.LockoutEnabled; editProfileViewModel.AccessFailedCount = userViewModel.AccessFailedCount; editProfileViewModel.status_key = userViewModel.status_key; editProfileViewModel.status_change_cas_key = userViewModel.status_change_cas_key; editProfileViewModel.status_change_date_forAll = userViewModel.status_change_date_forAll; editProfileViewModel.IsDeleted = userViewModel.IsDeleted; editProfileViewModel.ContractDate = userViewModel.ContractDate; editProfileViewModel.APIPassword = userViewModel.APIPassword; editProfileViewModel.CredentialCount = userViewModel.CredentialCount; editProfileViewModel.status_change_date = userViewModel.status_change_date; editProfileViewModel.AddressBlock = userViewModel.AddressBlock; editProfileViewModel.PhoneNumberConfirmed = userViewModel.PhoneNumberConfirmed; editProfileViewModel.EmailConfirmed = userViewModel.EmailConfirmed; editProfileViewModel.Gender = userViewModel.Gender; editProfileViewModel.IsTwoFactVerified = userViewModel.IsTwoFactVerified; editProfileViewModel.TwoFactVerifyCode = userViewModel.TwoFactVerifyCode; editProfileViewModel.CodeExpiryTime = userViewModel.CodeExpiryTime; _UserProfileService.EditUserProfile(editProfileViewModel); return(ShowSuccessMessageOnly("User Profile Successfully Edit..", user)); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); ModelState.AddModelError("", "Error! Please try again."); } return(GetErrorResult(userViewModel)); }
public bool GetCFDI(string user, string password, CFDI.Comprobante comprobante) { //throw new NotImplementedException(); string invoiceFileName = DateTime.Now.ToString("yyyyMMddHHmmss_" + comprobante.PublicKey.ToString("N")); byte[] sendFileBytes; byte[] responseFileBytes; CloudStorageAccount account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureDefaultStorageConnectionString"]); CloudBlobClient client = account.CreateCloudBlobClient(); CloudBlobContainer container = client.GetContainerReference(ConfigurationManager.AppSettings["AzureDefaultStorage"]); try { using (MemoryStream ms = new MemoryStream()) { using (MemoryStream zipMs = new MemoryStream()) { CFDIXmlTextWriter writer = new CFDIXmlTextWriter(comprobante, ms, System.Text.Encoding.UTF8); writer.WriteXml(); ms.Position = 0; using (ZipArchive zip = new ZipArchive(zipMs, ZipArchiveMode.Create, true)) { var entry = zip.CreateEntry(invoiceFileName + "_send.xml"); using (Stream s = entry.Open()) { ms.CopyTo(s); } zipMs.Flush(); } // zip.Dispose() => Close(); // container.CreateIfNotExists(); CloudBlockBlob blob = container.GetBlockBlobReference(invoiceFileName + "_send.zip"); zipMs.Position = 0; blob.UploadFromStream(zipMs); blob.Properties.ContentType = "application/x-zip-compressed"; blob.SetMetadata(); blob.SetProperties(); zipMs.Position = 0; sendFileBytes = zipMs.ToArray(); } // zipMs.Dispose() => Close(); } // ms.Dispose() => Close(); //CFDI.EDICOM.TestCFDI.CFDiService webService = new CFDI.EDICOM.TestCFDI.CFDiService(); //responseFileBytes = webService.getCfdiTest(user, password, sendFileBytes); ICFDIService webService = CFDiServiceFactory.Create(); responseFileBytes = webService.GetCFDI(user, password, sendFileBytes); CloudBlockBlob blob2 = container.GetBlockBlobReference(invoiceFileName + "_response.zip"); //zipMs.Position = 0; blob2.UploadFromByteArray(responseFileBytes, 0, responseFileBytes.Length); // .UploadFromStream(zipMs); blob2.Properties.ContentType = "application/x-zip-compressed"; blob2.SetMetadata(); blob2.SetProperties(); using (var responseStream = new MemoryStream(responseFileBytes)) { using (var archive = new ZipArchive(responseStream, ZipArchiveMode.Read, true)) { var fileInArchive = archive.Entries[0]; // using (var entryStream = fileInArchive.Open()) { using (var reader = new StreamReader(entryStream)) { string output = reader.ReadToEnd(); System.Xml.XmlDocument invoice = new System.Xml.XmlDocument(); invoice.LoadXml(output); System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(invoice.NameTable); nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"); nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"); System.Xml.XmlNode timbre = invoice.SelectSingleNode("//tfd:TimbreFiscalDigital", nsmgr); TimbreFiscalDigital complemento = new TimbreFiscalDigital(); complemento.Version = timbre.Attributes.GetNamedItem("version").Value.ToString(); complemento.UUID = timbre.Attributes.GetNamedItem("UUID").Value.ToString(); complemento.FechaTimbrado = DateTime.Parse(timbre.Attributes.GetNamedItem("FechaTimbrado").Value); complemento.SelloCFD = timbre.Attributes.GetNamedItem("selloCFD").Value.ToString(); complemento.NoCertificadoSAT = timbre.Attributes.GetNamedItem("noCertificadoSAT").Value.ToString(); complemento.SelloSAT = timbre.Attributes.GetNamedItem("selloSAT").Value.ToString(); if (comprobante.Complementos == null) { comprobante.Complementos = new List <Complemento>(); } comprobante.Complementos.Add(complemento); //Complemento complemento = new Complemento(); //complemento. // // Sistrategia.Server.SAT.CFDI.Comprobante comprobante2 = Sistrategia.Server.SAT.SATManager.GetComprobante(Guid.Parse(post["comprobanteId"])); // // comprobante2.Complemento = new Sistrategia.Server.SAT.CFDI.ComprobanteComplemento(); // // comprobante2.Complemento.TimbreFiscalDigitalSpecified = true; // // comprobante2.Complemento.TimbreFiscalDigital = new Sistrategia.Server.SAT.CFDI.ComprobanteTimbre(); // // comprobante2.Complemento.TimbreFiscalDigital.SatTimbreId = Guid.NewGuid(); // // comprobante2.Complemento.TimbreFiscalDigital.Version = timbre.Attributes.GetNamedItem("version").Value.ToString(); // // comprobante2.Complemento.TimbreFiscalDigital.UUID = timbre.Attributes.GetNamedItem("UUID").Value.ToString(); // // comprobante2.Complemento.TimbreFiscalDigital.FechaTimbrado = DateTime.Parse(timbre.Attributes.GetNamedItem("FechaTimbrado").Value); // // comprobante2.Complemento.TimbreFiscalDigital.SelloCFD = timbre.Attributes.GetNamedItem("selloCFD").Value.ToString(); // // comprobante2.Complemento.TimbreFiscalDigital.NoCertificadoSAT = timbre.Attributes.GetNamedItem("noCertificadoSAT").Value.ToString(); // // comprobante2.Complemento.TimbreFiscalDigital.SelloSAT = timbre.Attributes.GetNamedItem("selloSAT").Value.ToString(); // entryStream.Position = 0; // entryStream.Position // SAVE final xml: Sistrategia.SAT.CFDiWebSite.CloudStorage.CloudStorageMananger manager = new Sistrategia.SAT.CFDiWebSite.CloudStorage.CloudStorageMananger(); //manager.UploadFromStream(ConfigurationManager.AppSettings["AzureAccountName"], manager.UploadFromString(ConfigurationManager.AppSettings["AzureAccountName"], ConfigurationManager.AppSettings["AzureAccountKey"], comprobante.Emisor.PublicKey.ToString("N"), comprobante.PublicKey.ToString("N") + ".xml", comprobante.Serie + comprobante.Folio + ".xml", //model.ComprobanteArchivo.FileName, "text/xml", //model.ComprobanteArchivo.ContentType, output); // model.ComprobanteArchivo.InputStream); comprobante.GeneratedCadenaOriginal = comprobante.GetCadenaOriginal(); comprobante.GeneratedXmlUrl = string.Format(@"https://sistrategiacfdi1.blob.core.windows.net/{0}/{1}.xml", comprobante.Emisor.PublicKey.ToString("N"), comprobante.PublicKey.ToString("N")); comprobante.Status = "A"; } } //using (var fileToCompressStream = new MemoryStream(fileBytes)) { // fileToCompressStream.CopyTo(entryStream); //} } } } catch (Exception ex) { CloudBlockBlob blob2 = container.GetBlockBlobReference(invoiceFileName + "_exception.txt"); //zipMs.Position = 0; blob2.UploadText(ex.ToString()); blob2.Properties.ContentType = "text/plain"; blob2.SetMetadata(); blob2.SetProperties(); throw; } return(true); }
public void CloudStorageAccountClientUriVerify() { StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, true); CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("container1"); Assert.AreEqual(cloudStorageAccount.BlobEndpoint.ToString() + "container1", container.Uri.ToString()); CloudQueueClient queueClient = cloudStorageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("queue1"); Assert.AreEqual(cloudStorageAccount.QueueEndpoint.ToString() + "queue1", queue.Uri.ToString()); CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("table1"); Assert.AreEqual(cloudStorageAccount.TableEndpoint.ToString() + "table1", table.Uri.ToString()); }
/// <summary> /// Deletes the job and pool /// </summary> /// <param name="batchClient">The BatchClient to use when interacting with the Batch service.</param> /// <param name="jobId">The ID of the job.</param> /// <param name="blobContainerNames">The name of the containers created for the jobs resource files.</param> /// <returns>An asynchronous <see cref="Task"/> representing the operation.</returns> private async Task CleanupResourcesAsync(BatchClient batchClient, string jobId, IEnumerable<string> blobContainerNames) { // Delete the blob containers which contain the task input files since we no longer need them CloudStorageAccount storageAccount = new CloudStorageAccount( new StorageCredentials(this.configurationSettings.StorageAccountName, this.configurationSettings.StorageAccountKey), new Uri(this.configurationSettings.StorageBlobEndpoint), null, null, null); CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); foreach (string blobContainerName in blobContainerNames) { CloudBlobContainer container = cloudBlobClient.GetContainerReference(blobContainerName); Console.WriteLine("Deleting container: {0}", blobContainerName); await container.DeleteAsync(); } // Delete the job to ensure the tasks are cleaned up if (!string.IsNullOrEmpty(jobId) && this.configurationSettings.ShouldDeleteJob) { Console.WriteLine("Deleting job: {0}", jobId); await batchClient.JobOperations.DeleteJobAsync(jobId); } if (this.configurationSettings.ShouldDeletePool) { Console.WriteLine("Deleting pool: {0}", this.configurationSettings.PoolId); await batchClient.PoolOperations.DeletePoolAsync(this.configurationSettings.PoolId); } }