### Configure and Start WebJobs Host Source: https://github.com/azure/azure-webjobs-sdk/blob/dev/src/Microsoft.Azure.WebJobs.Host/README.md Demonstrates how to configure and start a WebJobs host in a console application using `Host.CreateDefaultBuilder` and `ConfigureWebJobs`. ```C# using System.Threading.Tasks; using Microsoft.Extensions.Hosting; class Program { public static async Task Main(string[] args) { var builder = Host.CreateDefaultBuilder(args) .ConfigureWebJobs(b => { b.AddAzureStorageCoreServices(); b.AddAzureStorageQueues(); }); using var host = builder.Build(); await host.RunAsync(); } } ``` -------------------------------- ### Basic BindToInput Rule Registration Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Example of registering a basic input rule using BindToInput with a converter. ```csharp IConverter builder = ...; // builder object to create a TObject instancef.BindToInput(builder); ``` -------------------------------- ### Using a String as Input with Custom Converter Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Example of a user function utilizing a custom converter, allowing a string to be bound as a SampleItem. ```csharp public void Reader( [QueueTrigger] string name, // from trigger [Sample(FileName = "{name}")] string contents) { ... } ``` -------------------------------- ### Using a Custom Input Binding in a Function Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Example of how a user function can utilize a custom input binding defined with BindToInput. ```csharp public void ReadSampleItem( [Queue] string name, [Sample(FileName = "{name}")] SampleItem item, TextWriter log) { log.WriteLine($"{item.Name}:{item.Contents}"); } ``` -------------------------------- ### Slack Binding with App Setting and Auto-Resolve Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings An example of a Slack binding attribute that utilizes both [AppSetting] for the WebHookUrl and [AutoResolve] for other parameters like Text, Username, IconEmoji, and Channel. ```csharp [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue)] [Binding] public sealed class SlackAttribute : Attribute { [AppSetting(Default = "SlackWebHookKeyName")] public string WebHookUrl { get; set; } [AutoResolve] public string Text { get; set; } [AutoResolve] public string Username { get; set; } [AutoResolve] public string IconEmoji { get; set; } [AutoResolve] public string Channel { get; set; } } ``` -------------------------------- ### QueueTrigger Function with Timeout Source: https://github.com/azure/azure-webjobs-sdk/blob/dev/src/Microsoft.Azure.WebJobs/README.md Example of a QueueTrigger function that specifies a timeout of 15 minutes using the TimeoutAttribute. ```C# using Microsoft.Azure.WebJobs; [TimeoutAttribute("00:15:00")] public void ProcessWorkItem([QueueTrigger("test")] WorkItem workItem, ILogger logger) { logger.LogInformation($"Processed work item {workItem.ID}"); } ``` -------------------------------- ### Implementing Invocation and Exception Filters Directly in a Job Class Source: https://github.com/azure/azure-webjobs-sdk/wiki/Function-Filters This example demonstrates a job class that directly implements both IFunctionExceptionFilter and IFunctionInvocationFilter interfaces, allowing for custom logic before and after function execution, and during exceptions. ```csharp public class Functions : IFunctionExceptionFilter, IFunctionInvocationFilter { public void ProcessWorkItem( [QueueTrigger("test")] WorkItem workItem) { Console.WriteLine($"Processed work item {workItem.ID}"); } public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken) { // TODO: your logic here return Task.CompletedTask; } public Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancellationToken) { // TODO: your logic here return Task.CompletedTask; } public Task OnExecutedAsync(FunctionExecutedContext executedContext, CancellationToken cancellationToken) { // TODO: your logic here return Task.CompletedTask; } } ``` -------------------------------- ### Define a Binding Attribute Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings This is a C# example of defining a binding attribute. It uses the `AttributeUsage` and `Binding` meta-attributes. ```csharp [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue)] [Binding] public sealed class DocumentDBAttribute : Attribute ``` -------------------------------- ### Registering a BindToCollector Rule Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Register a rule to support outputting discrete messages using BindToCollector. This example shows binding for ITableEntity. ```csharp var rule = context.AddBindingRule(); rule.BindToCollector(builder); ``` -------------------------------- ### Event Hub Binding with App Setting Support Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Demonstrates how to use the [AppSetting] attribute to allow the 'Connection' property of a binding to be resolved from application settings. ```csharp public sealed class EventHubAttribute : Attribute, IConnectionProvider { // Other properties ... [AppSetting] public string Connection { get; set; } } ``` -------------------------------- ### Configure Application Insights Logging in WebJobs Source: https://github.com/azure/azure-webjobs-sdk/blob/dev/src/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/README.md Demonstrates how to configure Application Insights logging on host startup using the `AddApplicationInsightsWebJobs` builder method. Ensure the `APPINSIGHTS_INSTRUMENTATIONKEY` is set in your configuration. ```csharp using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; class Program { public static async Task Main(string[] args) { var builder = Host.CreateDefaultBuilder(args) .ConfigureWebJobs(b => { b.AddAzureStorageCoreServices(); b.AddAzureStorageQueues(); }) .ConfigureLogging((context, b) => { // If this key exists in any config, use it to enable App Insights string appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]; if (!string.IsNullOrEmpty(appInsightsKey)) { b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = appInsightsKey); } }); using var host = builder.Build(); await host.RunAsync(); } } ``` -------------------------------- ### Set DefaultConnectionLimit in WebJobs Main Method Source: https://github.com/azure/azure-webjobs-sdk/wiki/ServicePointManager-settings-for-WebJobs Configure the maximum number of concurrent connections to a specific host by setting ServicePointManager.DefaultConnectionLimit in the Main method before initializing the JobHost. This is crucial for preventing connection bottlenecks and ensuring optimal performance. ```csharp static void Main(string[] args) { // Set this immediately so that it is used by all requests. ServicePointManager.DefaultConnectionLimit = Int32.MaxValue; var host = new JobHost(); host.RunAndBlock(); } ``` -------------------------------- ### Applying Function Filters with Attributes Source: https://github.com/azure/azure-webjobs-sdk/wiki/Function-Filters Demonstrates how to apply an exception filter at the class level and an invocation filter at the method level to Azure Functions. ```csharp using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; public class WorkItem { public string ID { get; set; } public int Priority { get; set; } } public class ValidationException : Exception { public ValidationException(string message) : base(message) { } } [ErrorHandler] public static class Functions { public static void BlobTrigger( [BlobTrigger("test")] string blob) { Console.WriteLine("Processed blob: " + blob); } [WorkItemValidator] public static void ProcessWorkItem( [QueueTrigger("test")] WorkItem workItem) { Console.WriteLine($"Processed work item {workItem.ID}"); } } ``` -------------------------------- ### Register Custom gRPC Extension in WebJobs SDK Source: https://github.com/azure/azure-webjobs-sdk/blob/dev/src/Microsoft.Azure.WebJobs.Extensions.Rpc/README.md Demonstrates how an extension can register a custom gRPC service using `MapWorkerGrpcService`. This method is called on the `IWebJobsBuilder` to integrate the custom service. ```csharp public static IWebJobsBuilder AddMyExtension(this IWebJobsBuilder builder, Action configure) { builder.AddExtension() .MapWorkerGrpcService(); builder.Services.AddSingleton(); return builder; } ``` -------------------------------- ### Blob Binding with Auto-Resolve for Path Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Shows how the [AutoResolve] attribute enables dynamic resolution of binding parameters like the blob path, supporting both app settings and runtime data. ```csharp class Payload { public string name {get;set; } } void Foo([QueueTrigger] Payload msg, [Blob("%container%/{name}")] TextReader reader) { ... } ``` -------------------------------- ### Registering a Converter for Input Binding Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Define a converter to transform a string into a custom SampleItem for input bindings. This converter is used within the Initialize method. ```csharp public void Initialize(ExtensionConfigContext context) { ... context.AddConverter(ConvertToString); ... } private SampleItem ConvertToItem(string arg) { var parts = arg.Split(':'); return new SampleItem { Name = parts[0], Contents = parts[1] }; } ``` -------------------------------- ### Registering a Global Function Invocation Filter Source: https://github.com/azure/azure-webjobs-sdk/wiki/Function-Filters This snippet shows how to register a custom IFunctionInvocationFilter globally using the ExtensionRegistry in the JobHostConfiguration. ```csharp var extensions = config.GetService(); extensions.RegisterExtension(myFilter); ``` -------------------------------- ### Registering a BindToInput Rule Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Register a rule to bind custom attributes to input types. This rule is invoked per function execution. ```csharp public class SampleExtensions : IExtensionConfigProvider { public void Initialize(ExtensionConfigContext context) { context.AddConverter(ConvertToString); // Create an input rules for the Sample attribute. var rule = context.AddBindingRule(); rule.BindToInput(BuildItemFromAttr); } private SampleItem BuildItemFromAttr(SampleAttribute attribute) { ... return new SampleItem { Name = attribute.FileName, Contents = contents }; } } ``` -------------------------------- ### Registering a Generic Converter with OpenType Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Register a generic converter for a custom type using OpenType as a placeholder for the generic type T. The SDK determines the correct value for T during runtime. ```csharp cm.AddConverter>(typeof(CustomConverter<>)); ``` -------------------------------- ### Custom Converter Implementation for Generic Types Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Implement a custom converter that handles generic types. This converter deserializes input contents into the generic type T and creates a CustomType object. ```csharp private class CustomConverter : IConverter> { public CustomType Convert(SampleItem input) { // Do some custom logic to create a CustomType<> var contents = input.Contents; T obj = JsonConvert.DeserializeObject(contents); return new CustomType { Name = input.Name, Value = obj }; } } ``` -------------------------------- ### Custom Exception Filter for Error Handling Source: https://github.com/azure/azure-webjobs-sdk/wiki/Function-Filters Defines a custom exception filter that logs errors when a function fails. This can be extended for custom error handling logic. ```csharp public class ErrorHandlerAttribute : FunctionExceptionFilterAttribute { public override Task OnExceptionAsync( FunctionExceptionContext exceptionContext, CancellationToken cancellationToken) { // custom error handling logic could be written here // (e.g. write a queue message, send a notification, etc.) exceptionContext.Logger.LogError( $"ErrorHandler called. Function '{exceptionContext.FunctionName}"+ ":{exceptionContext.FunctionInstanceId} failed."); return Task.CompletedTask; } } ``` -------------------------------- ### User Function Using Custom Generic Type Binding Source: https://github.com/azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings A user function that utilizes a custom generic type, CustomType, for input binding. This demonstrates how custom converters enable binding to specific generic types. ```csharp public class CustomType { public string Name { get; set; } public T Value; } public void AnotherReader( [Queue] string name, [Sample(Name = "{name}")] CustomType item, TextWriter log) { log.WriteLine($"Via custom type {item.Name}:{item.Value}"); } ``` -------------------------------- ### Custom Invocation Filter for Work Item Validation Source: https://github.com/azure/azure-webjobs-sdk/wiki/Function-Filters Defines a custom invocation filter that validates a WorkItem argument before function execution. Throws a ValidationException if validation fails. ```csharp public class WorkItemValidatorAttribute : FunctionInvocationFilterAttribute { public override Task OnExecutingAsync( FunctionExecutingContext executingContext, CancellationToken cancellationToken) { executingContext.Logger.LogInformation("WorkItemValidator executing..."); var workItem = executingContext.Arguments.First().Value as WorkItem; string errorMessage = null; if (!TryValidateWorkItem(workItem, out errorMessage)) { executingContext.Logger.LogError(errorMessage); throw new ValidationException(errorMessage); } return base.OnExecutingAsync(executingContext, cancellationToken); } private static bool TryValidateWorkItem(WorkItem workItem, out string errorMessage) { errorMessage = null; if (string.IsNullOrEmpty(workItem.ID)) { errorMessage = "ID cannot be null or empty."; return false; } if (workItem.Priority > 100 || workItem.Priority < 0) { errorMessage = "Priority must be between 0 and 100"; return false; } return true; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.