public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string errorMixQuery = req.Query["errormix"]; string mockServiceName = (string)req.Query["name"] ?? "Hello.Functions.PostMock"; InsightsHelper.TrackEvent(mockServiceName, req); // if an errorMix query param is provided as an integer value between 1 and 100 (inclusive) if (int.TryParse(errorMixQuery, out int errorMix) && errorMix > 0 && errorMix <= 100) { // if random number (between 0 and 100) is greater-than-equal-to (100 - errorMix) if ((new Random().NextDouble() * 100d) >= (100 - errorMix)) { log.LogInformation($"Returning HTTP Status 429. Errormix = {errorMix}"); return(new StatusCodeResult(429)); } } string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); return(new JsonResult(data)); }
static async Task Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) //.AddEnvironmentVariables() .Build(); var insights = InsightsHelper.InitializeTelemetryClient( config, "Examples.Pipeline.MessageGenerator", $"cloudRoleInstance-{Environment.MachineName}"); int rpm = args.Length > 0 ? int.Parse(args[0]) : 60; var client = new QueueClient(config["ServiceBusConnectionString"], config["MessageGenerator.QueueName"]); Console.WriteLine($"Sending messages at ~{rpm} RPM to queue \"{config["MessageGenerator.QueueName"]}\"."); insights.TrackTrace($"Sending messages at {rpm} RPM to queue \"{config["MessageGenerator.QueueName"]}\"."); int errors = 0; int i = 1; while (1 == 1) { try { // Create a new message to send to the queue. string messageBody = $"Message {i}"; var message = new Message(Encoding.UTF8.GetBytes(messageBody)); message.UserProperties.Add("MessageNumber", i); // Write the body of the message to the console. Console.WriteLine($"Sending message: {messageBody}"); // Send the message to the queue. await client.SendAsync(message); insights.TrackEvent( "Examples.Pipeline.MessageGenerator/QueueMessageSent", new Dictionary <string, string>( message.UserProperties.Select(p => new KeyValuePair <string, string>(p.Key, p.Value.ToString())))); } catch (Exception exception) { errors++; Console.Error.WriteLine($"Message {i} :: Exception: {exception.Message}"); insights.TrackException(exception); if (errors > 10) { throw; } } await Task.Delay(60000 / rpm); i++; } }
static async Task Main() { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) //.AddEnvironmentVariables() .Build(); _insights = InsightsHelper.InitializeTelemetryClient( config, "Examples.Pipeline.ServiceBusReceiver", $"cloudRoleInstance-{Environment.MachineName}" ); _queueClient = new QueueClient(config["ServiceBusConnectionString"], config["ServiceBusReceiver.QueueName"]); // Register QueueClient's MessageHandler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(_queueClient); Console.WriteLine($"Ready: {_queueClient}"); while (true) { await Task.Delay(200); } //await _queueClient.CloseAsync(); }
public IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { _config = FunctionsHelper.GetConfig(context); _log = log; string url = req.Query["url"]; if (!IsWhitelisted(url)) { return(new NotFoundResult()); } log.LogInformation($"Redirect: 302 {url}"); InsightsHelper.TrackEvents(_telemetryClient, "FunMetrics.Redirect", url, req); return(new RedirectResult(url, false)); }
public static async Task <IEnumerable <Product> > Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); InsightsHelper.TrackEvent("products/get-modified", req); bool.TryParse(req.Query["modified"], out bool modified); // Mock Data return(new Product[] { new Product { Id = "fa28f4e040f94c8da37aa9d50cf385cb", Name = "KORIK RISE GTX", SKUs = new SKU[] { new SKU { SkuName = "42 Black", SuggestedRetailPrice = 150, WholesalePrice = 75 }, new SKU { SkuName = "43 Black", SuggestedRetailPrice = 150, WholesalePrice = 75 }, new SKU { SkuName = "44 Black", SuggestedRetailPrice = 150, WholesalePrice = 75 } } } }); }
static async Task Main(string[] args) { Console.WriteLine("Examples.Pipeline.EventProcessor"); var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) //.AddEnvironmentVariables() .Build(); var insights = InsightsHelper.InitializeTelemetryClient( config, "Examples-Pipeline-EventProcessor", $"cloudRoleInstance-{Environment.MachineName}"); var observer = new EventProcessorObserver(); var host = InitializeEventProcessorHost(config); await host.RegisterEventProcessorFactoryAsync( new ForwardToQueueEventProcessorFactory(config, insights, observer), new EventProcessorOptions { MaxBatchSize = 100, PrefetchCount = 200 }); Console.WriteLine($"Ready: {host}"); while (true) { await Task.Delay(10000); Console.WriteLine("============================"); Console.WriteLine(observer.GetMetricsString()); } }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "head", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { _config = FunctionsHelper.GetConfig(context); string path = req.Query["path"]; log.LogInformation($"FunMetrics.Blob.Run: {req.Method} {path}"); if (string.IsNullOrWhiteSpace(path)) { log.LogError("Querystring param \"path\" is null, empty or missing."); return(new NotFoundResult()); } if (path.StartsWith('/') || !path.Contains('/')) { log.LogError("Querystring param \"path\" is malformed. Must be a relative path to a blob file, with no leading \"/\"."); return(new NotFoundResult()); } var uri = new Uri($"{CloudBlobClient.BaseUri}{path}"); log.LogInformation($"FunMetrics.Blob.Run: {req.Method} {uri}"); ICloudBlob blob; try { blob = await CloudBlobClient.GetBlobReferenceFromServerAsync(uri); } catch (StorageException ex) { log.LogError(ex, "Returning 404 / Not found."); return(new NotFoundResult()); } if (req.Method == HttpMethods.Head) { // HEAD - Return empty body but with headers as if GET req.HttpContext.Response.Headers["ETag"] = blob.Properties.ETag; req.HttpContext.Response.ContentLength = blob.Properties.Length; req.HttpContext.Response.ContentType = blob.Properties.ContentType; if (blob.Properties.LastModified.HasValue) { req.HttpContext.Response.Headers["Last-Modified"] = blob.Properties.LastModified.Value.ToString("r"); } return(new OkResult()); } // GET - get blob and stream to client InsightsHelper.TrackEvents(_telemetryClient, "FunMetrics.Blob", uri.ToString(), req); Stream stream = null; // try local cache #if DEBUG string cachePath = Path.GetTempPath(); #else string cachePath = "D:\\Local\\"; #endif string filePath = $"{cachePath}{path.Replace("/", "__")}"; bool cacheError = false; if (File.Exists(filePath)) { // retry three times for (int i = 0; i < 3; i++) { // get from local cache try { stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); log.LogInformation($"FunMetrics.Blob.Run: Cache HIT {filePath}"); break; } catch (Exception ex) { log.LogError(ex, $"Could not open file \"{filePath}\" on attempt {i + 1}: {ex} {ex.Message}"); await Task.Delay(10); } cacheError = true; } } if (stream == null) { // get from Blob log.LogInformation($"FunMetrics.Blob.Run: Cache MISS {filePath}"); stream = new MemoryStream(); await blob.DownloadToStreamAsync(stream); // don't try to save to cache if could not read from cache. File exists, was busy if (!cacheError) { // save to cache try { using (var fileStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } } catch (Exception ex) { log.LogError(ex, $"Could not cache file \"{filePath}\"."); } } } stream.Seek(0, SeekOrigin.Begin); return(new FileStreamResult(stream, blob.Properties.ContentType) { EnableRangeProcessing = true, EntityTag = new EntityTagHeaderValue(blob.Properties.ETag), LastModified = blob.Properties.LastModified }); }