private static async Task <Func <BlobContinuationToken, Task <BlobResultSegment> > > GetBlobsForPath( string path, IBinder binder, ILogger log) { var attr = new BlobAttribute(path) { Connection = "ImageStorageAccount" }; if (path.Split('/').Length == 1) { var container = await binder.BindAsync <CloudBlobContainer>(attr); log.LogInformation($"Operating on container {container.Name}."); return(container.ListBlobsSegmentedAsync); } else { var directory = await binder.BindAsync <CloudBlobDirectory>(attr); log.LogInformation($"Operating on directory {directory.Prefix}"); return(directory.ListBlobsSegmentedAsync); } }
public async Task UpdateDurationAsync(long id, IBinder binder, CancellationToken token) { //var id = RegEx.NumberExtractor.Match(assetName).Value; var containerName = await _videoService.GetAssetContainerAsync(id, AssetType.Long, token); var container = await binder.BindAsync <CloudBlobContainer>(new BlobAttribute(containerName), token); var blobs = await container.ListBlobsSegmentedAsync(null, null); var blob = blobs.Results.OfType <CloudBlockBlob>() .First(f => f.Name.EndsWith("manifest.json")); var str = await blob.DownloadTextAsync(); dynamic json = JToken.Parse(str); string durationXml = json.AssetFile[0].Duration; var v = XmlConvert.ToTimeSpan(durationXml); var blobDirectoryFiles = await binder.BindAsync <IEnumerable <CloudBlockBlob> >(new BlobAttribute($"spitball-files/files/{id}"), token); var originalVideoBlob = blobDirectoryFiles.Single(s => s.Name.Contains("/file-", StringComparison.OrdinalIgnoreCase)); var url = originalVideoBlob.GetDownloadLink(TimeSpan.FromHours(1)); await _videoService.CreatePreviewJobAsync(id, url.AbsoluteUri, v, token); var command = UpdateDocumentMetaCommand.Video(id, v); await _commandBus.DispatchAsync(command, token); }
public static async Task <IActionResult> Run( [HttpTrigger( AuthorizationLevel.Function, nameof(HttpMethods.Post), Route = null)] Player player, IBinder binder) { var serializedPlayer = JsonConvert.SerializeObject(player); var cloudQueueMessage = new CloudQueueMessage(serializedPlayer); // Not WindowsAzure.Storage.Queue! IActionResult result = null; if (string.IsNullOrEmpty(player.Id)) { var queueAttribute = new QueueAttribute(QueueConfig.NewPlayerErrorItems); var cloudQueue = await binder.BindAsync <CloudQueue>(queueAttribute); await cloudQueue.AddMessageAsync(cloudQueueMessage); result = new BadRequestObjectResult("No player data in request."); } else { var queueAttribute = new QueueAttribute(QueueConfig.NewPlayerItems); var cloudQueue = await binder.BindAsync <CloudQueue>(queueAttribute); await cloudQueue.AddMessageAsync(cloudQueueMessage); result = new AcceptedResult(); } return(result); }
public static async Task <IActionResult> Update( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "update/{hostname}")] HttpRequest req, IBinder binder, string hostname, ILogger log) { log.LogInformation($"Update request for {hostname}"); string currentClientIp = GetIpFromRequestHeaders(req); log.LogInformation($"Client IP: {currentClientIp.Substring(0,6)}"); string existingIp = null; string zoneIdentifier = null; string recordIdentifier = null; zoneIdentifier = req.Query[nameof(zoneIdentifier)]; recordIdentifier = req.Query[nameof(recordIdentifier)]; using (var reader = await binder.BindAsync <TextReader>(new BlobAttribute( $"registrations/{hostname.Replace('.','-')}.txt", FileAccess.Read))) { existingIp = await reader.ReadLineAsync(); if (existingIp == currentClientIp) { log.LogInformation("Same IP, skipping update"); return(new OkObjectResult("ok")); } // we need to update log.LogInformation("Updating IP in Cloudflare..."); if (string.IsNullOrWhiteSpace(zoneIdentifier) || string.IsNullOrWhiteSpace(recordIdentifier)) { zoneIdentifier = await reader.ReadLineAsync(); recordIdentifier = await reader.ReadLineAsync(); } }; log.LogInformation($"ZoneId: {zoneIdentifier}, Record: {recordIdentifier}"); log.LogInformation($"Updating {hostname} from {currentClientIp}"); var cloudFlare = new CloudflareClient(Environment.GetEnvironmentVariable("CLOUDFLARE_APITOKEN")); await cloudFlare.UpdateDnsZone(hostname, zoneIdentifier, recordIdentifier, currentClientIp); log.LogInformation("IP Updated"); using (var writer = await binder.BindAsync <TextWriter>(new BlobAttribute( $"registrations/{hostname.Replace('.', '-')}.txt", FileAccess.Write))) { string blobRegistrationContent = currentClientIp + Environment.NewLine + zoneIdentifier + Environment.NewLine + recordIdentifier; await writer.WriteAsync(blobRegistrationContent); }; return(new OkObjectResult("ok")); }
public static async Task <IActionResult> RunDocumentImageAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = UrlConst.ImageFunctionDocumentRoute)] HttpRequest req, long id, IBinder binder, //collector search duplicate so i added some search 3 to solve this [Queue("generate-blob-preview")] IAsyncCollector <string> collectorSearch3, Microsoft.Extensions.Logging.ILogger logger, [Blob("spitball-files/files/{id}/preview-0.jpg")] CloudBlockBlob blob, CancellationToken token) { var mutation = ImageMutation.FromQueryString(req.Query); try { await using var sr = await blob.OpenReadAsync(); var image = ProcessImage(sr, mutation); return(new ImageResult(image, TimeSpan.FromDays(365))); } catch (ImageFormatException ex) { logger.LogError(ex, id.ToString()); return(new RedirectResult(blob.Uri.AbsoluteUri)); } catch (StorageException e) { if (e.RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound) { throw; } var t1 = collectorSearch3.AddAsync(id.ToString(), token); var directoryBlobs = await binder.BindAsync <IEnumerable <ICloudBlob> >(new BlobAttribute($"spitball-files/files/{id}"), token); var blobPath = "spitball-user/DefaultThumbnail/doc-preview-empty.png"; var fileBlob = directoryBlobs.FirstOrDefault(f => f.Name.Contains("/file-")); var blobExtension = Path.GetExtension(fileBlob?.Name)?.ToLower(); if (blobExtension != null && FileTypesExtensions.FileExtensionsMapping.TryGetValue(blobExtension, out var val)) { blobPath = $"spitball-user/DefaultThumbnail/{val.DefaultThumbnail}"; } var t2 = binder.BindAsync <Stream>(new BlobAttribute(blobPath, FileAccess.Read), token); await Task.WhenAll(t1, t2); using (t2.Result) { var image = ProcessImage(t2.Result, mutation); return(new ImageResult(image, TimeSpan.Zero)); } } }
public static async Task Run( [QueueTrigger("transmission-faults", Connection = "AzureWebJobsStorage")] string fault, IBinder blobFaultBinder, TraceWriter log) { var faultData = JsonConvert.DeserializeObject <TransmissionFaultMessage>(fault); var blobReader = await blobFaultBinder.BindAsync <CloudBlockBlob>( new BlobAttribute($"transmission-faults/{faultData.id}", FileAccess.ReadWrite)); var json = await blobReader.DownloadTextAsync(); try { List <string> faultMessages = await Task <List <string> > .Factory.StartNew(() => JsonConvert.DeserializeObject <List <string> >(json)); await Utils.obHEC(faultMessages, log); } catch { log.Error($"FaultProcessor failed to send to Splunk: {faultData.id}"); return; } await blobReader.DeleteAsync(); log.Info($"C# Queue trigger function processed: {faultData.id}"); }
public static async Task Run( [QueueTrigger("orders", Connection = "AzureWebJobsStorage")] Order order, //[Blob("licenses/{rand-guid}.lic")] TextWriter outputBlob, IBinder blobBinder, ILogger log) { var outputBlob = await blobBinder.BindAsync <TextWriter>( new BlobAttribute(blobPath : $"licenses/{order.OrderId}.lic") { Connection = "AzureWebJobsStorage" }); outputBlob.WriteLine($"OrderId:{order.OrderId}"); outputBlob.WriteLine($"Email:{order.Email}"); outputBlob.WriteLine($"ProductId:{order.ProductId}"); outputBlob.WriteLine($"PurchaseDate:{DateTime.UtcNow}"); var md5 = System.Security.Cryptography.MD5.Create(); var hash = md5.ComputeHash( System.Text.Encoding.UTF8.GetBytes(order.Email + "secret")); outputBlob.WriteLine($"secret: {BitConverter.ToString(hash).Replace("-", "")}"); log.LogInformation($"C# Queue trigger function processed: {order}"); }
public static async Task <IActionResult> Run( [HttpTrigger( AuthorizationLevel.Function, nameof(HttpMethods.Get), Route = null)] HttpRequest request, IBinder binder) { string id = request.Query["id"]; IActionResult result; if (string.IsNullOrEmpty(id)) { result = new BadRequestObjectResult("No player data in request."); } else { string content; var blobAttribute = new BlobAttribute($"players/in/player-{id}.json"); using (var input = await binder.BindAsync <TextReader>(blobAttribute)) { content = await input.ReadToEndAsync(); } result = new ContentResult { Content = content, ContentType = MediaTypeNames.Application.Json, StatusCode = 200 }; } return(result); }
public async Task <IActionResult> Negotiate( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "messaging/negotiate")] HttpRequest req, IBinder binder) { string userId = req.Headers["X-User-Id"]; if (!Guid.TryParse(userId, out Guid userIdGuid)) { _logger.LogError($"User call to /negotiate did not include a valid GUID in the header. We found '{userId}' in the X-User-Id header."); return(new BadRequestResult()); } // Force override of the SignalR user ID. // Normally this method would be decorated with a [SignalRConnectionInfo] attribute, which would be // where we could set the UserId attribute by using function dot-binding, i.e. UserId = "{headers.x-user-id}". // Unfortunately, the only headers visible to the function seem to be the Azure Auth-based claims headers, // and we're sending up a custom user ID. // So instead, we short-circuit the normal binding process, forcibly create our own binding attribute by hand, // at a point in time where we have access to our user ID, and then tell the binder to use that instead. SignalRConnectionInfoAttribute attribute = new SignalRConnectionInfoAttribute { HubName = Constants.ChatHubName, UserId = userIdGuid.ToIdString(), }; SignalRConnectionInfo info = await binder.BindAsync <SignalRConnectionInfo>(attribute); return(new OkObjectResult(info)); }
public static async Task <IActionResult> RunAsync( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, IBinder binder, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { string partitionKey = req.Query["partitionKey"]; string rowKey = req.Query["rowKey"]; var table = await binder.BindAsync <LoggerEventModel>(new TableAttribute($"tablecurd", $"{partitionKey}", $"{rowKey}") { Connection = "TableConnection" }); return(new OkObjectResult(table)); } catch (StorageException e) { Console.WriteLine(e.Message); Console.ReadLine(); throw; } }
public static async Task Run( [QueueTrigger("orders", Connection = "AzureWebJobsStorage")] Order order, IBinder binder, ILogger log) { var outputBlob = await binder.BindAsync <TextWriter>( new BlobAttribute($"licenses/{order.OrderId}.lic") { Connection = "AzureWebJobStorage" } ); await outputBlob.WriteLineAsync($"OrderId: {order.OrderId}"); await outputBlob.WriteLineAsync($"Email: {order.Email}"); await outputBlob.WriteLineAsync($"ProductId: {order.ProductId}"); await outputBlob.WriteLineAsync($"PurchaseDate: {DateTime.UtcNow}"); var md5 = System.Security.Cryptography.MD5.Create(); var hash = md5.ComputeHash( System.Text.Encoding.UTF8.GetBytes(order.Email + "secret")); await outputBlob.WriteLineAsync($"SecretCode: {BitConverter.ToString(hash).Replace("-", "")}"); }
private static async Task WriteAuditContainerAsync(IBinder binder, string prefix, ICommand command, ICommandResult commandResult, string providerId) { var tasks = new List <Task>() { WriteBlobAsync(command) }; if (commandResult != null) { tasks.Add(WriteBlobAsync(commandResult)); } await Task .WhenAll(tasks) .ConfigureAwait(false); async Task WriteBlobAsync(object data) { #pragma warning disable CA1308 // Normalize strings to uppercase var auditPath = $"{prefix.ToLowerInvariant()}-audit/{command.ProjectId}/{command.CommandId}/{providerId}/{data.GetType().Name}.json"; var auditBlob = await binder .BindAsync <CloudBlockBlob>(new BlobAttribute(auditPath.Replace("//", "/", StringComparison.OrdinalIgnoreCase))) .ConfigureAwait(false); await auditBlob .UploadTextAsync(JsonConvert.SerializeObject(data, Formatting.Indented)) .ConfigureAwait(false); #pragma warning restore CA1308 // Normalize strings to uppercase } }
public async Task UpdateSummary(IBinder binder, ILogger log) { var blob = await binder.BindAsync <CloudBlockBlob>(new BlobAttribute(SUMMARY_PATH)); var data = new Dictionary <int, AbilityHistoryData>(); var abilities = this.metaClient.GetSkills().Where(_ => _.AbilityDraftEnabled).ToList(); foreach (var ability in abilities) { try { var attr = new BlobAttribute(string.Format(HISTORY_PATH, ability.Id)); var history = await ReadData <AbilityHistory>(binder, attr); var model = new AbilityHistoryData() { Total = history.Total, Current = history.Current, Previous = history.Previous }; data.Add(ability.Id, model); } catch (Exception) { } } Action <AbilitySummary> updateFn = (summary) => summary.Data = data; await ProcessBlob(blob, updateFn, log); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, IBinder binder, TraceWriter log) { log.Info("RetrieveArray was triggered!"); string jsonContent = await req.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject <RetrieveArrayInputModel>(jsonContent); if (string.IsNullOrWhiteSpace(data.Key)) { return(req.CreateResponse(HttpStatusCode.BadRequest)); } var valueString = await binder.BindAsync <SortArrayTableEntity>( new TableAttribute("SortArrayAzureFuncTable", PartitionKey, data.Key)); if (valueString == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } var resultArray = JsonConvert.DeserializeObject <int[]>(valueString.Values); Array.Sort(resultArray); return(req.CreateResponse(HttpStatusCode.OK, new { key = data.Key, ArrayOfValues = resultArray })); }
public static async Task QueueTrigger([QueueTrigger("%WaitTimesUpdatesQueue%")] string myQueueItem, IBinder inputBinder, [DocumentDB("%DocDBDatabase%", "%DocDBCollection%", ConnectionStringSetting = "DocDBConnectionString")] IAsyncCollector <dynamic> collector, TraceWriter log) { log.Info($"Queue trigger function processed a message: {myQueueItem}"); // read the clockwise data var hospitals = await GetWaitsAsync(myQueueItem); // read the urgent care facilities var documentDbAttribute = new DocumentDBAttribute(ConfigurationManager.AppSettings["DocDBDatabase"], ConfigurationManager.AppSettings["DocDBCollection"]) { ConnectionStringSetting = "DocDBConnectionString", SqlQuery = $"SELECT * FROM uc WHERE uc.hospitalId IN ({string.Join(",", hospitals.Select(h => h.HospitalId))}) ORDER BY uc._ts desc" // -- UCOMMENT FOR CASE USING OWN ID --- //SqlQuery = $"SELECT * FROM uc WHERE uc.id IN ({string.Join(",", hospitals.Select(h => $"\"{h.HospitalId}\""))}) ORDER BY uc._ts desc" }; var inputDocuments = await inputBinder.BindAsync <IEnumerable <UrgentCareCenter> >(documentDbAttribute); // update the wait times foreach (var urgentCareFacility in inputDocuments) { var hospital = hospitals.SingleOrDefault(h => h.HospitalId == urgentCareFacility.HospitalId); // -- UCOMMENT FOR CASE USING OWN ID --- //var hospital = hospitals.SingleOrDefault(h => h.HospitalId == int.Parse(urgentCareFacility.Id)); urgentCareFacility.CurrentWaitRangeHigh = hospital.CurrentWaitRangeHigh; urgentCareFacility.CurrentWaitRangeLow = hospital.CurrentWaitRangeLow; await collector.AddAsync(urgentCareFacility); } }
public async Task UpdateSummary(IBinder binder, ILogger log) { var blob = await binder.BindAsync <CloudBlockBlob>(new BlobAttribute(SUMMARY_PATH)); var data = new Dictionary <int, HeroHistoryData>(); var heroes = this.metaClient.GetADHeroes(); foreach (var hero in heroes) { try { var attr = new BlobAttribute(string.Format(HISTORY_PATH, hero.Id)); var history = await ReadData <HeroHistory>(binder, attr); var model = new HeroHistoryData() { Total = history.Total, Current = history.Current, Previous = history.Previous }; data.Add(hero.Id, model); } catch (Exception) { } } Action <HeroSummary> updateFn = (summary) => summary.Data = data; await ProcessBlob(blob, updateFn, log); }
private async Task UpdateDetails(Match match, Player player, IBinder binder, ILogger log) { if (player.ability_upgrades == null) { return; } var attr = new BlobAttribute(string.Format(DETAILS_PATH, player.hero_id)); var blob = await binder.BindAsync <CloudBlockBlob>(attr); Action <HeroCombo> updateFn = (details) => { var victory = match.Victory(player); var abilities = player.ability_upgrades.Select(_ => _.ability).Distinct().ToList(); foreach (var id in abilities) { var item = details.Data.Find(_ => _.Id == id); if (item == null) { item = new HeroComboStat() { Id = id }; details.Data.Add(item); } item.Update(victory); } }; await ProcessBlob(blob, updateFn, log); }
private async Task UpdateHistory(Match match, Player player, IBinder binder, ILogger log) { var attr = new BlobAttribute(string.Format(HISTORY_PATH, player.hero_id)); var blob = await binder.BindAsync <CloudBlockBlob>(attr); Action <HeroHistory> updateFn = (history) => { var victory = match.Victory(player); var date = DateTimeOffset.FromUnixTimeSeconds(match.start_time); var bounds = date.AddDays(-6); var mid = date.AddDays(-3); history.Total.Picks++; history.Total.Wins += victory ? 1 : 0; history.Data.Add(new HeroHistoryVictory() { Timestamp = date, Victory = victory }); history.Data.RemoveAll(_ => _.Timestamp < bounds); var current = history.Data.Where(_ => _.Timestamp > mid).ToList(); var previous = history.Data.Where(_ => _.Timestamp < mid).ToList(); history.Current.Picks = current.Count(); history.Current.Wins = current.Count(_ => _.Victory == true); history.Previous.Picks = previous.Count; history.Previous.Wins = previous.Count(_ => _.Victory == true); }; await ProcessBlob(blob, updateFn, log); }
public static async Task Run( [QueueTrigger("orders", Connection = "AzureWebJobsStorage")] Order order, IBinder binder, ILogger log) { //IBinder interface need to provide two type of infos: 1: binding attribute 2: the type we binding to //For 1st info works with all binding attributes (eg. QueueAttibute, SendGridAttribute) //since we constructure the attribute inside the method body, we can calculate parameters on-demand in the body //not only we can customzie the path paramater we can also pass in different storage connection //for 2nd info Ibinder makes it very flexible to choose the type to bind to at runtime, here we choose TextWriter var outputBlob = await binder.BindAsync <TextWriter>( new BlobAttribute($"licenses/{order.OrderId}.lic") { Connection = "AzureWebJobsStorage" }); outputBlob.WriteLine($"OrderId: {order.OrderId}"); outputBlob.WriteLine($"Email: {order.Email}"); outputBlob.WriteLine($"ProductId: {order.ProductId}"); outputBlob.WriteLine($"PurchaseDate: {DateTime.UtcNow}"); var md5 = System.Security.Cryptography.MD5.Create(); var hash = md5.ComputeHash( System.Text.Encoding.UTF8.GetBytes(order.Email + "secret")); outputBlob.WriteLine($"SecretCode: {BitConverter.ToString(hash).Replace("-", "")}"); log.LogInformation($"LicenseFile generated successfully"); }
public static async Task EmailLicenseFileActivity( [ActivityTrigger] Order order, [SendGrid(ApiKey = "SendGridApiKey")] ICollector <SendGridMessage> sender, IBinder binder, ILogger log) { var licenseFileContents = await binder.BindAsync <string>( new BlobAttribute($"licenses/{order.Id}.lic")); var email = order.Email; log.LogInformation($"Got order from {email}\n Order Id:{order.Id}"); var message = new SendGridMessage(); message.From = new EmailAddress(Environment.GetEnvironmentVariable("EmailSender")); message.AddTo(email); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(licenseFileContents); var base64 = Convert.ToBase64String(plainTextBytes); message.AddAttachment($"{order.Id}.lic", base64, "text/plain"); message.Subject = "Your license file"; message.HtmlContent = "Thank you for your order"; if (!email.EndsWith("@test.com")) { sender.Add(message); } }
public static async Task <IActionResult> RunAsync( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, IBinder binder, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var data = JsonConvert.DeserializeObject <LoggerEventModel>(requestBody); var table = await binder.BindAsync <CloudTable>(new TableAttribute($"tablecurd") { Connection = "TableConnection" }); var operation = TableOperation.Insert(data); await table.ExecuteAsync(operation); return(new OkObjectResult("created")); } catch (StorageException e) { Console.WriteLine(e.Message); Console.ReadLine(); throw; } }
public static async Task <IActionResult> RunAsync( [HttpTrigger(AuthorizationLevel.Function, "delete", Route = null)] HttpRequest req, IBinder binder, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { string PrimaryKey = req.Query["PrimaryKey"]; string RowKey = req.Query["RowKey"]; var table = await binder.BindAsync <CloudTable>(new TableAttribute($"tablecurd") { Connection = "TableConnection" }); var item = new TableEntity(PrimaryKey, RowKey) { ETag = "*" }; var operation = TableOperation.Delete(item); await table.ExecuteAsync(operation); return(new OkObjectResult("deleted")); } catch (StorageException e) { Console.WriteLine(e.Message); Console.ReadLine(); throw; } }
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, CloudBlockBlob outputBlob, IBinder binder, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); //req.Content.ReadAsStringAsync(); string requestBody = new StreamReader(req.Body).ReadToEnd(); dynamic data = JsonConvert.DeserializeObject(requestBody); var name = data?.name; var webClient = new WebClient(); byte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png"); outputBlob.Uri.ToString(); outputBlob.UploadFromByteArrayAsync(imageBytes, 0, 1000).RunSynchronously(); var date = DateTime.Now.ToString("yyyyMMddhhmmss"); using (var writer = binder.BindAsync <BinaryWriter>(new TableAttribute("Post", DateTime.Now.Year.ToString(), date)).Result) { writer.Write(imageBytes); } return(name != null ? (ActionResult) new OkObjectResult($"Hello, {name}") : new BadRequestObjectResult("Please pass a name on the query string or in the request body")); }
public static async Task Run( [BlobTrigger("licenses/{orderId}.lic", Connection = "AzureWebJobsStorage")] string licenseFileContents, [SendGrid(ApiKey = "SendGridApiKey")] ICollector <SendGridMessage> mailSender, IBinder binder, string orderId, ILogger log) { var order = await binder.BindAsync <Order>( new TableAttribute("orders", "orders", orderId) { Connection = "AzureWebJobsStorage" }); var message = new SendGridMessage(); message.From = new EmailAddress(Environment.GetEnvironmentVariable("EmailSender")); message.AddTo(order.Email); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(licenseFileContents); var base64 = Convert.ToBase64String(plainTextBytes); message.AddAttachment(filename: orderId + ".lic", content: base64, type: "text/plain"); message.Subject = "Your license file"; message.HtmlContent = "Thank you for your order"; mailSender.Add(message); log.LogInformation("Email Sent Successfully!"); }
public async Task DoOperationAsync(RedeemTransactionMessage msg, IBinder binder, CancellationToken token) { var query = new RedeemEmailQuery(msg.TransactionId); var result = await _queryBus.QueryAsync(query, token); if (result is null) { return; } var message = new SendGridMessage(); message.AddContent("text/html", $"User id: {result.UserId} want to redeem {result.Amount}"); var culture = new CultureInfo("en"); if (result.Country.Equals("IN", StringComparison.OrdinalIgnoreCase)) { culture = new CultureInfo("en-IN"); } CultureInfo.CurrentCulture = CultureInfo.DefaultThreadCurrentCulture = culture; var emailTo = ResourceWrapper.GetString("email_support"); message.AddTo(emailTo); var emailProvider = await binder.BindAsync <IAsyncCollector <SendGridMessage> >(new SendGridAttribute() { ApiKey = "SendgridKey", From = "Spitball <*****@*****.**>", Subject = $"Redeem Email {result.UserId}" }, token); await emailProvider.AddAsync(message, token); }
private static async Task LogFailuresToAzureStuff <T>(IBinder blobFaultBinder, Binder queueFaultBinder, ILogger log, List <string> parsedMessages, Exception exEmit) { string id = Guid.NewGuid().ToString(); log.LogError($"Failed to write the fault queue: {id}. {exEmit}"); try { CloudBlockBlob blobWriter = await blobFaultBinder.BindAsync <CloudBlockBlob>(new BlobAttribute($"transmission-faults/{id}", FileAccess.ReadWrite)); string json = await Task <string> .Factory.StartNew(() => JsonConvert.SerializeObject(parsedMessages)); await blobWriter.UploadTextAsync(json); } catch (Exception exFaultBlob) { log.LogError($"Failed to write the fault blob: {id}. {exFaultBlob}"); } try { TransmissionFaultMessage qMsg = new TransmissionFaultMessage { id = id, type = typeof(T).ToString() }; string qMsgJson = JsonConvert.SerializeObject(qMsg); CloudQueue queueWriter = await queueFaultBinder.BindAsync <CloudQueue>(new QueueAttribute("transmission-faults")); await queueWriter.AddMessageAsync(new CloudQueueMessage(qMsgJson)); } catch (Exception exFaultQueue) { log.LogError($"Failed to write the fault queue: {id}. {exFaultQueue}"); } }
public static async Task <IActionResult> RunAsync( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, IBinder binder, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); var table = await binder.BindAsync <CloudTable>(new TableAttribute($"tablecurd") { Connection = "TableConnection" }); try { TableContinuationToken token = null; var entities = new List <LoggerEventModel>(); do { var queryResult = table.ExecuteQuerySegmented(new TableQuery <LoggerEventModel>(), token); entities.AddRange(queryResult.Results); token = queryResult.ContinuationToken; } while (token != null); return(new OkObjectResult(entities)); } catch (StorageException e) { Console.WriteLine(e.Message); Console.ReadLine(); throw; } }
public static async Task <IActionResult> Run( [HttpTrigger( AuthorizationLevel.Function, "post", Route = null)] Player player, IBinder binder) { //playerBlob = default; IActionResult result; if (player == null) { result = new BadRequestObjectResult("No player data in request."); } else { // playerBlob = JsonConvert.SerializeObject(player, Formatting.Indented); var blobAttribute1 = new BlobAttribute($"players/out/dynamic-{player.Id}"); var blobAttribute = new BlobAttribute($"players/out/dynamic-{player.Id}.json"); using (var output = await binder.BindAsync <TextWriter>(blobAttribute)) { await output.WriteAsync(JsonConvert.SerializeObject(player)); } result = new AcceptedResult(); } return(result); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, IBinder binder, TraceWriter log) { log.Info("SubmitArray was triggered!"); string jsonContent = await req.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject <SortArrayInputModel>(jsonContent); if (string.IsNullOrWhiteSpace(data.Key) || data.ArrayOfValues == null || data.ArrayOfValues.Length == 0) { return(req.CreateResponse(HttpStatusCode.BadRequest)); } var collector = await binder.BindAsync <IAsyncCollector <SortArrayTableEntity> >( new TableAttribute("SortArrayAzureFuncTable")); await collector.AddAsync(new SortArrayTableEntity { RowKey = data.Key, PartitionKey = PartitionKey, Values = JsonConvert.SerializeObject(data.ArrayOfValues) }); return(req.CreateResponse(HttpStatusCode.OK, new { })); }
public async static Task Run([QueueTrigger("queue-image-delete")] MessageImage message, IBinder binder, ILogger log) { log.LogInformation($"Função ativada!"); var blobAtributte = new BlobAttribute(message.ImageUri, FileAccess.Read); var cloudBlobStream = await binder.BindAsync <ICloudBlob>(blobAtributte); await cloudBlobStream.DeleteIfExistsAsync(); await cloudBlobStream.Container.SetPermissionsAsync(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Blob }); var connectionString = Environment.GetEnvironmentVariable("SqlConnectionString"); using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); var textSql = $@"DELETE FROM [dbo].[BibliotecaMusical] WHERE Id = {message.Id}"; using (SqlCommand cmd = new SqlCommand(textSql, conn)) { var rowsAffected = cmd.ExecuteNonQuery(); log.LogInformation($"rowsAffected: {rowsAffected}"); } } log.LogInformation($"Função encerrada!"); }