mirror of https://github.com/dotnet/tye.git
committed by
GitHub
150 changed files with 6696 additions and 15 deletions
@ -0,0 +1,77 @@ |
|||
# Using Tye and Azure Functions |
|||
|
|||
[Azure Functions](https://azure.microsoft.com/en-us/services/functions/) is a popular serverless compute platform from Azure. Tye supports running Azure functions locally. |
|||
|
|||
## Getting Started: Create an Azure Function |
|||
|
|||
Starting from the [sample here](https://github.com/dotnet/tye/tree/master/samples/frontend-backend), we are going to transform the backend from a web application to an azure function app. |
|||
|
|||
To start, create an Azure Function project in a folder called `backend-function`. You can do this via: |
|||
- [Visual Studio Code](https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-function-vs-code?pivots=programming-language-csharp) |
|||
- [Visual Studio](https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio) |
|||
- [Commandline](https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-azure-function-azure-cli?tabs=bash%2Cbrowser&pivots=programming-language-csharp) |
|||
|
|||
Next, create an HttpTrigger called `MyHttpTrigger` in your functions project. Change the contents of MyHttpTrigger to the following: |
|||
|
|||
```c# |
|||
[FunctionName("MyHttpTrigger")] |
|||
public static async Task<IActionResult> Run( |
|||
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, |
|||
ILogger log) |
|||
{ |
|||
log.LogInformation("C# HTTP trigger function processed a request."); |
|||
|
|||
var backendInfo = new BackendInfo() |
|||
{ |
|||
IP = req.HttpContext.Connection.LocalIpAddress.ToString(), |
|||
Hostname = System.Net.Dns.GetHostName(), |
|||
}; |
|||
|
|||
return new OkObjectResult(backendInfo); |
|||
} |
|||
|
|||
class BackendInfo |
|||
{ |
|||
public string IP { get; set; } = default!; |
|||
|
|||
public string Hostname { get; set; } = default!; |
|||
} |
|||
``` |
|||
|
|||
Finally, change line in the frontend's `Startup.cs` to call the right endpoint (line 63), changing "/" to "api/MyHttpTrigger". |
|||
|
|||
```c# |
|||
endpoints.MapGet("/", async context => |
|||
{ |
|||
var bytes = await httpClient.GetByteArrayAsync("/api/MyHttpTrigger"); |
|||
var backendInfo = JsonSerializer.Deserialize<BackendInfo>(bytes, options); |
|||
... |
|||
} |
|||
``` |
|||
|
|||
## Adding your Azure Function in tye.yaml |
|||
|
|||
Now that we have a backend function added, you can simply modify your tye.yaml to point to the azure function instead: |
|||
|
|||
```yaml |
|||
# tye application configuration file |
|||
# read all about it at https://github.com/dotnet/tye |
|||
name: frontend-backend |
|||
services: |
|||
- name: backend |
|||
azureFunction: backend-function/ # folder path to the azure function. |
|||
- name: frontend |
|||
project: frontend/frontend.csproj |
|||
``` |
|||
|
|||
## Running locally |
|||
|
|||
You can now run the application locally by doing `tye run`. |
|||
|
|||
On first run of an app that requires functions, tye will install any tools necessary to run functions apps in the future. This may take a while on first run, but will be saved afterwards. |
|||
|
|||
Navigate to the tye dashboard to see both the frontend and backend running. Navigate to the frontend to see that the app still has the same behavior as before. |
|||
|
|||
## Deployment |
|||
|
|||
Deployment of azure functions is currently not supported. |
|||
@ -0,0 +1,7 @@ |
|||
# Azure function support details in Tye |
|||
|
|||
- supports v2 and v3 functions |
|||
- Specify v2 or v3 in tye.yaml |
|||
- Specify x64 or x86 in tye.yaml (defaults to x64) |
|||
- Specify another path to func.exe |
|||
|
|||
@ -0,0 +1,199 @@ |
|||
root = true |
|||
|
|||
[*] |
|||
indent_style = space |
|||
|
|||
[*.{props,targets,csproj}] |
|||
indent_style = space |
|||
indent_size = 2 |
|||
|
|||
[*.{js,json}] |
|||
indent_style = space |
|||
indent_size = 2 |
|||
|
|||
[*.{yml,yaml}] |
|||
indent_style = space |
|||
indent_size = 2 |
|||
|
|||
[*.{cs,csx}] |
|||
indent_size = 4 |
|||
insert_final_newline = true |
|||
charset = utf-8-bom |
|||
|
|||
# Code files |
|||
[*.{cs,csx,vb,vbx}] |
|||
indent_size = 4 |
|||
insert_final_newline = true |
|||
charset = utf-8-bom |
|||
|
|||
# Powershell files |
|||
[*.ps1] |
|||
indent_size = 2 |
|||
|
|||
# Shell script files |
|||
[*.sh] |
|||
end_of_line = lf |
|||
indent_size = 2 |
|||
|
|||
# Dotnet code style settings: |
|||
[*.{cs,vb}] |
|||
# Sort using and Import directives with System.* appearing first |
|||
dotnet_sort_system_directives_first = true |
|||
# Avoid "this." and "Me." if not necessary |
|||
dotnet_style_qualification_for_field = false:refactoring |
|||
dotnet_style_qualification_for_property = false:refactoring |
|||
dotnet_style_qualification_for_method = false:refactoring |
|||
dotnet_style_qualification_for_event = false:refactoring |
|||
|
|||
# Use language keywords instead of framework type names for type references |
|||
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion |
|||
dotnet_style_predefined_type_for_member_access = true:suggestion |
|||
|
|||
# Suggest more modern language features when available |
|||
dotnet_style_object_initializer = true:suggestion |
|||
dotnet_style_collection_initializer = true:suggestion |
|||
dotnet_style_coalesce_expression = true:suggestion |
|||
dotnet_style_null_propagation = true:suggestion |
|||
dotnet_style_explicit_tuple_names = true:suggestion |
|||
|
|||
# Non-private static fields are PascalCase |
|||
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion |
|||
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields |
|||
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style |
|||
|
|||
dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field |
|||
dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected |
|||
dotnet_naming_symbols.non_private_static_fields.required_modifiers = static |
|||
|
|||
dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case |
|||
|
|||
# Non-private readonly fields are PascalCase |
|||
dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion |
|||
dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields |
|||
dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style |
|||
|
|||
dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field |
|||
dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected |
|||
dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = readonly |
|||
|
|||
dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case |
|||
|
|||
# Constants are PascalCase |
|||
dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion |
|||
dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants |
|||
dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style |
|||
|
|||
dotnet_naming_symbols.constants.applicable_kinds = field, local |
|||
dotnet_naming_symbols.constants.required_modifiers = const |
|||
|
|||
dotnet_naming_style.constant_style.capitalization = pascal_case |
|||
|
|||
# Static fields are camelCase |
|||
dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion |
|||
dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields |
|||
dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style |
|||
|
|||
dotnet_naming_symbols.static_fields.applicable_kinds = field |
|||
dotnet_naming_symbols.static_fields.required_modifiers = static |
|||
|
|||
dotnet_naming_style.static_field_style.capitalization = camel_case |
|||
|
|||
# Instance fields are camelCase |
|||
dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion |
|||
dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields |
|||
dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style |
|||
|
|||
dotnet_naming_symbols.instance_fields.applicable_kinds = field |
|||
|
|||
dotnet_naming_style.instance_field_style.capitalization = camel_case |
|||
|
|||
# Locals and parameters are camelCase |
|||
dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion |
|||
dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters |
|||
dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style |
|||
|
|||
dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local |
|||
|
|||
dotnet_naming_style.camel_case_style.capitalization = camel_case |
|||
|
|||
# Local functions are PascalCase |
|||
dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion |
|||
dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions |
|||
dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style |
|||
|
|||
dotnet_naming_symbols.local_functions.applicable_kinds = local_function |
|||
|
|||
dotnet_naming_style.local_function_style.capitalization = pascal_case |
|||
|
|||
# By default, name items with PascalCase |
|||
dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion |
|||
dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members |
|||
dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style |
|||
|
|||
dotnet_naming_symbols.all_members.applicable_kinds = * |
|||
|
|||
dotnet_naming_style.pascal_case_style.capitalization = pascal_case |
|||
|
|||
[*.cs] |
|||
# Newline settings |
|||
csharp_new_line_before_open_brace = all |
|||
csharp_new_line_before_else = true |
|||
csharp_new_line_before_catch = true |
|||
csharp_new_line_before_finally = true |
|||
csharp_new_line_before_members_in_object_initializers = true |
|||
csharp_new_line_before_members_in_anonymous_types = true |
|||
csharp_new_line_between_query_expression_clauses = true |
|||
|
|||
# Indentation preferences |
|||
csharp_indent_block_contents = true |
|||
csharp_indent_braces = false |
|||
csharp_indent_case_contents = true |
|||
csharp_indent_case_contents_when_block = true |
|||
csharp_indent_switch_labels = true |
|||
csharp_indent_labels = flush_left |
|||
|
|||
# Prefer "var" everywhere |
|||
csharp_style_var_for_built_in_types = true:suggestion |
|||
csharp_style_var_when_type_is_apparent = true:suggestion |
|||
csharp_style_var_elsewhere = true:suggestion |
|||
|
|||
# Prefer method-like constructs to have a block body |
|||
csharp_style_expression_bodied_methods = false:none |
|||
csharp_style_expression_bodied_constructors = false:none |
|||
csharp_style_expression_bodied_operators = false:none |
|||
|
|||
# Prefer property-like constructs to have an expression-body |
|||
csharp_style_expression_bodied_properties = true:none |
|||
csharp_style_expression_bodied_indexers = true:none |
|||
csharp_style_expression_bodied_accessors = true:none |
|||
|
|||
# Suggest more modern language features when available |
|||
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion |
|||
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion |
|||
csharp_style_inlined_variable_declaration = true:suggestion |
|||
csharp_style_throw_expression = true:suggestion |
|||
csharp_style_conditional_delegate_call = true:suggestion |
|||
|
|||
# Space preferences |
|||
csharp_space_after_cast = false |
|||
csharp_space_after_colon_in_inheritance_clause = true |
|||
csharp_space_after_comma = true |
|||
csharp_space_after_dot = false |
|||
csharp_space_after_keywords_in_control_flow_statements = true |
|||
csharp_space_after_semicolon_in_for_statement = true |
|||
csharp_space_around_binary_operators = before_and_after |
|||
csharp_space_around_declaration_statements = do_not_ignore |
|||
csharp_space_before_colon_in_inheritance_clause = true |
|||
csharp_space_before_comma = false |
|||
csharp_space_before_dot = false |
|||
csharp_space_before_open_square_brackets = false |
|||
csharp_space_before_semicolon_in_for_statement = false |
|||
csharp_space_between_empty_square_brackets = false |
|||
csharp_space_between_method_call_empty_parameter_list_parentheses = false |
|||
csharp_space_between_method_call_name_and_opening_parenthesis = false |
|||
csharp_space_between_method_call_parameter_list_parentheses = false |
|||
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false |
|||
csharp_space_between_method_declaration_name_and_open_parenthesis = false |
|||
csharp_space_between_method_declaration_parameter_list_parentheses = false |
|||
csharp_space_between_parentheses = false |
|||
csharp_space_between_square_brackets = false |
|||
@ -0,0 +1,12 @@ |
|||
# VotingSample |
|||
Voting sample app inspired by https://github.com/dockersamples/example-voting-app with a few different implementation choices. This voting app uses [Azure Functions](https://azure.microsoft.com/en-us/services/functions/) with a Queue and Http function. |
|||
|
|||
## For running |
|||
|
|||
To run, first make sure the azure storage emulator is running. You can use [Azurite](https://docs.microsoft.com/en-us/azure/storage/common/storage-use-azurite) cross platform or use the [Azure Storage Emulator](https://docs.microsoft.com/en-us/azure/storage/common/storage-use-emulator?toc=/azure/storage/blobs/toc.json) on Windows. |
|||
|
|||
Next, all you need to do is execute `tye run` and navigate to the dashboard. |
|||
|
|||
## For deployment |
|||
|
|||
Deployment is currently not supported for Azure Functions. |
|||
@ -0,0 +1,21 @@ |
|||
apiVersion: extensions/v1beta1 |
|||
kind: Ingress |
|||
metadata: |
|||
name: ingress-basic |
|||
namespace: default |
|||
annotations: |
|||
kubernetes.io/ingress.class: nginx |
|||
nginx.ingress.kubernetes.io/ssl-redirect: "false" |
|||
nginx.ingress.kubernetes.io/rewrite-target: /$2 |
|||
spec: |
|||
rules: |
|||
- http: |
|||
paths: |
|||
- backend: |
|||
serviceName: vote |
|||
servicePort: 80 |
|||
path: /vote(/|$)(.*) |
|||
- backend: |
|||
serviceName: results |
|||
servicePort: 80 |
|||
path: /results(/|$)(.*) |
|||
@ -0,0 +1,10 @@ |
|||
<Router AppAssembly="@typeof(Program).Assembly"> |
|||
<Found Context="routeData"> |
|||
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> |
|||
</Found> |
|||
<NotFound> |
|||
<LayoutView Layout="@typeof(MainLayout)"> |
|||
<p>Sorry, there's nothing at this address.</p> |
|||
</LayoutView> |
|||
</NotFound> |
|||
</Router> |
|||
@ -0,0 +1,13 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
|
|||
namespace Results |
|||
{ |
|||
public class VotingResult |
|||
{ |
|||
public string Vote { get; set; } |
|||
public int Count { get; set; } |
|||
} |
|||
} |
|||
@ -0,0 +1,16 @@ |
|||
@page "/error" |
|||
|
|||
|
|||
<h1 class="text-danger">Error.</h1> |
|||
<h2 class="text-danger">An error occurred while processing your request.</h2> |
|||
|
|||
<h3>Development Mode</h3> |
|||
<p> |
|||
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred. |
|||
</p> |
|||
<p> |
|||
<strong>The Development environment shouldn't be enabled for deployed applications.</strong> |
|||
It can result in displaying sensitive information from exceptions to end users. |
|||
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong> |
|||
and restarting the app. |
|||
</p> |
|||
@ -0,0 +1,113 @@ |
|||
@page "/" |
|||
@implements IDisposable |
|||
@using System.Text.Json; |
|||
@using System.Threading |
|||
@using Microsoft.Extensions.Configuration |
|||
@using Microsoft.AspNetCore.SignalR.Client |
|||
@using ChartJs.Blazor.Charts |
|||
@using ChartJs.Blazor.ChartJS.Common.Properties |
|||
@using ChartJs.Blazor.Util |
|||
@using ChartJs.Blazor.ChartJS.PieChart |
|||
|
|||
|
|||
@inject IConfiguration Configuration |
|||
|
|||
@* <div id="result"> |
|||
<span>Dog Votes: @DogVotes.Count</span> |
|||
<span>Cat Votes: @CatVotes.Count</span> |
|||
</div> *@ |
|||
|
|||
<div id="result"> |
|||
<ChartJsPieChart @ref="_pieChartJs" Config="@_config" Width="600" Height="300" /> |
|||
</div> |
|||
|
|||
@code { |
|||
private VotingResult DogVotes = new VotingResult { Vote = "a", Count = 0 }; |
|||
private VotingResult CatVotes = new VotingResult { Vote = "b", Count = 0 }; |
|||
|
|||
private PieConfig _config; |
|||
private ChartJsPieChart _pieChartJs; |
|||
|
|||
private HttpClient _client = new HttpClient(); |
|||
|
|||
protected override void OnInitialized() |
|||
{ |
|||
_config = new PieConfig |
|||
{ |
|||
Options = new PieOptions |
|||
{ |
|||
Title = new OptionsTitle |
|||
{ |
|||
Display = true, |
|||
Text = "Dogs vs Cats" |
|||
}, |
|||
Responsive = true, |
|||
Animation = new ArcAnimation |
|||
{ |
|||
AnimateRotate = true, |
|||
AnimateScale = true |
|||
} |
|||
} |
|||
}; |
|||
|
|||
_config.Data.Labels.AddRange(new[] { "Dogs", "Cats" }); |
|||
|
|||
var pieSet = new PieDataset |
|||
{ |
|||
BackgroundColor = new[] { ColorUtil.RandomColorString(), ColorUtil.RandomColorString() }, |
|||
BorderWidth = 0, |
|||
HoverBackgroundColor = ColorUtil.RandomColorString(), |
|||
HoverBorderColor = ColorUtil.RandomColorString(), |
|||
HoverBorderWidth = 1, |
|||
BorderColor = "#ffffff", |
|||
}; |
|||
|
|||
pieSet.Data.AddRange(new double[] { DogVotes.Count, CatVotes.Count }); |
|||
_config.Data.Datasets.Add(pieSet); |
|||
} |
|||
|
|||
protected override async Task OnAfterRenderAsync(bool firstRender) |
|||
{ |
|||
if (firstRender) |
|||
{ |
|||
_ = Connect(); |
|||
} |
|||
} |
|||
|
|||
async Task Connect() |
|||
{ |
|||
try |
|||
{ |
|||
var response = await _client.GetStringAsync(Configuration.GetServiceUri("worker")!.AbsoluteUri + "api/GetResults"); |
|||
var results = JsonSerializer.Deserialize<VotingResult[]>(response); |
|||
//Reset votes because if there are zero votes there will be no entry from the query. |
|||
DogVotes = new VotingResult { Vote = "a", Count = 0 }; |
|||
CatVotes = new VotingResult { Vote = "b", Count = 0 }; |
|||
|
|||
foreach (var vote in results) |
|||
{ |
|||
if (vote.Vote == "a") |
|||
{ |
|||
DogVotes = vote; |
|||
} |
|||
else |
|||
{ |
|||
CatVotes = vote; |
|||
} |
|||
} |
|||
|
|||
_config.Data.Datasets[0].Data.Clear(); |
|||
_config.Data.Datasets[0].Data.Add(DogVotes.Count); |
|||
_config.Data.Datasets[0].Data.Add(CatVotes.Count); |
|||
await _pieChartJs.Update(); |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
Console.WriteLine(ex.Message); |
|||
} |
|||
} |
|||
|
|||
void IDisposable.Dispose() |
|||
{ |
|||
} |
|||
} |
|||
@ -0,0 +1,51 @@ |
|||
@page "/" |
|||
@namespace Results.Pages |
|||
@using Microsoft.Extensions.Hosting; |
|||
@inject IHostEnvironment env |
|||
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers |
|||
@{ |
|||
Layout = null; |
|||
} |
|||
|
|||
<!DOCTYPE html> |
|||
<html lang="en"> |
|||
<head> |
|||
@if(!env.IsDevelopment()) |
|||
{ |
|||
<base href="/results/" > |
|||
} |
|||
<meta charset="utf-8" /> |
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
|||
<title>Results</title> |
|||
<base href="~/" /> |
|||
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" /> |
|||
<link href="css/site.css" rel="stylesheet" /> |
|||
<link rel="stylesheet" href="_content/ChartJs.Blazor/ChartJSBlazor.css" /> |
|||
</head> |
|||
<body> |
|||
<app> |
|||
<component type="typeof(App)" render-mode="ServerPrerendered" /> |
|||
</app> |
|||
|
|||
<div id="blazor-error-ui"> |
|||
<environment include="Staging,Production"> |
|||
An error has occurred. This application may no longer respond until reloaded. |
|||
</environment> |
|||
<environment include="Development"> |
|||
An unhandled exception has occurred. See browser dev tools for details. |
|||
</environment> |
|||
<a href="" class="reload">Reload</a> |
|||
<a class="dismiss">🗙</a> |
|||
</div> |
|||
|
|||
<script src="_framework/blazor.server.js"></script> |
|||
<!-- Reference the included moment.js javascript file. --> |
|||
<script src="_content/ChartJs.Blazor/moment-with-locales.min.js" type="text/javascript" language="javascript"></script> |
|||
|
|||
<!-- Reference the included ChartJs javascript file. --> |
|||
<script src="_content/ChartJs.Blazor/Chart.min.js" type="text/javascript" language="javascript"></script> |
|||
|
|||
<!-- This is the glue between the C# code and the ChartJs charts --> |
|||
<script src="_content/ChartJs.Blazor/ChartJsBlazorInterop.js" type="text/javascript" language="javascript"></script> |
|||
</body> |
|||
</html> |
|||
@ -0,0 +1,28 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.IO; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore; |
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Extensions.Hosting; |
|||
using Microsoft.Extensions.Logging; |
|||
|
|||
namespace Results |
|||
{ |
|||
public class Program |
|||
{ |
|||
public static void Main(string[] args) |
|||
{ |
|||
CreateHostBuilder(args).Build().Run(); |
|||
} |
|||
|
|||
public static IHostBuilder CreateHostBuilder(string[] args) => |
|||
Host.CreateDefaultBuilder(args) |
|||
.ConfigureWebHostDefaults(webBuilder => |
|||
{ |
|||
webBuilder.UseStartup<Startup>(); |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
{ |
|||
"iisSettings": { |
|||
"windowsAuthentication": false, |
|||
"anonymousAuthentication": true, |
|||
"iisExpress": { |
|||
"applicationUrl": "http://localhost:41343", |
|||
"sslPort": 44346 |
|||
} |
|||
}, |
|||
"profiles": { |
|||
"IIS Express": { |
|||
"commandName": "IISExpress", |
|||
"launchBrowser": true, |
|||
"environmentVariables": { |
|||
"ASPNETCORE_ENVIRONMENT": "Development" |
|||
} |
|||
}, |
|||
"results": { |
|||
"commandName": "Project", |
|||
"launchBrowser": true, |
|||
"applicationUrl": "http://localhost:5005", |
|||
"environmentVariables": { |
|||
"ASPNETCORE_ENVIRONMENT": "Development" |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,7 @@ |
|||
@inherits LayoutComponentBase |
|||
|
|||
<div class="main"> |
|||
<div class="content px-4"> |
|||
@Body |
|||
</div> |
|||
</div> |
|||
@ -0,0 +1,55 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Builder; |
|||
using Microsoft.AspNetCore.Components; |
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.AspNetCore.HttpsPolicy; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Hosting; |
|||
|
|||
namespace Results |
|||
{ |
|||
public class Startup |
|||
{ |
|||
public Startup(IConfiguration configuration) |
|||
{ |
|||
Configuration = configuration; |
|||
} |
|||
|
|||
public IConfiguration Configuration { get; } |
|||
|
|||
// This method gets called by the runtime. Use this method to add services to the container.
|
|||
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
|
|||
public void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
services.AddRazorPages(); |
|||
services.AddServerSideBlazor(); |
|||
} |
|||
|
|||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
|||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) |
|||
{ |
|||
if (env.IsDevelopment()) |
|||
{ |
|||
app.UseDeveloperExceptionPage(); |
|||
} |
|||
else |
|||
{ |
|||
app.UseExceptionHandler("/Error"); |
|||
} |
|||
|
|||
app.UseStaticFiles(); |
|||
|
|||
app.UseRouting(); |
|||
|
|||
app.UseEndpoints(endpoints => |
|||
{ |
|||
endpoints.MapBlazorHub(); |
|||
endpoints.MapFallbackToPage("/_Host"); |
|||
}); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
@using System.Net.Http |
|||
@using Microsoft.AspNetCore.Authorization |
|||
@using Microsoft.AspNetCore.Components.Authorization |
|||
@using Microsoft.AspNetCore.Components.Forms |
|||
@using Microsoft.AspNetCore.Components.Routing |
|||
@using Microsoft.AspNetCore.Components.Web |
|||
@using Microsoft.JSInterop |
|||
@using Results |
|||
@using Results.Shared |
|||
@ -0,0 +1,10 @@ |
|||
{ |
|||
"DetailedErrors": true, |
|||
"Logging": { |
|||
"LogLevel": { |
|||
"Default": "Information", |
|||
"Microsoft": "Warning", |
|||
"Microsoft.Hosting.Lifetime": "Information" |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,10 @@ |
|||
{ |
|||
"Logging": { |
|||
"LogLevel": { |
|||
"Default": "Information", |
|||
"Microsoft": "Warning", |
|||
"Microsoft.Hosting.Lifetime": "Information" |
|||
} |
|||
}, |
|||
"AllowedHosts": "*" |
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk.Web"> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>netcoreapp3.1</TargetFramework> |
|||
<RootNamespace>Results</RootNamespace> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="ChartJs.Blazor" Version="1.0.3" /> |
|||
<PackageReference Include="dapper" Version="2.0.30" /> |
|||
<PackageReference Include="microsoft.aspnetcore.signalr.client" Version="3.1.3" /> |
|||
<PackageReference Include="npgsql" Version="4.1.3.1" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="$(TyeLibrariesPath)\Microsoft.Tye.Extensions.Configuration\Microsoft.Tye.Extensions.Configuration.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,86 @@ |
|||
SIL OPEN FONT LICENSE Version 1.1 |
|||
|
|||
Copyright (c) 2014 Waybury |
|||
|
|||
PREAMBLE |
|||
The goals of the Open Font License (OFL) are to stimulate worldwide |
|||
development of collaborative font projects, to support the font creation |
|||
efforts of academic and linguistic communities, and to provide a free and |
|||
open framework in which fonts may be shared and improved in partnership |
|||
with others. |
|||
|
|||
The OFL allows the licensed fonts to be used, studied, modified and |
|||
redistributed freely as long as they are not sold by themselves. The |
|||
fonts, including any derivative works, can be bundled, embedded, |
|||
redistributed and/or sold with any software provided that any reserved |
|||
names are not used by derivative works. The fonts and derivatives, |
|||
however, cannot be released under any other type of license. The |
|||
requirement for fonts to remain under this license does not apply |
|||
to any document created using the fonts or their derivatives. |
|||
|
|||
DEFINITIONS |
|||
"Font Software" refers to the set of files released by the Copyright |
|||
Holder(s) under this license and clearly marked as such. This may |
|||
include source files, build scripts and documentation. |
|||
|
|||
"Reserved Font Name" refers to any names specified as such after the |
|||
copyright statement(s). |
|||
|
|||
"Original Version" refers to the collection of Font Software components as |
|||
distributed by the Copyright Holder(s). |
|||
|
|||
"Modified Version" refers to any derivative made by adding to, deleting, |
|||
or substituting -- in part or in whole -- any of the components of the |
|||
Original Version, by changing formats or by porting the Font Software to a |
|||
new environment. |
|||
|
|||
"Author" refers to any designer, engineer, programmer, technical |
|||
writer or other person who contributed to the Font Software. |
|||
|
|||
PERMISSION & CONDITIONS |
|||
Permission is hereby granted, free of charge, to any person obtaining |
|||
a copy of the Font Software, to use, study, copy, merge, embed, modify, |
|||
redistribute, and sell modified and unmodified copies of the Font |
|||
Software, subject to the following conditions: |
|||
|
|||
1) Neither the Font Software nor any of its individual components, |
|||
in Original or Modified Versions, may be sold by itself. |
|||
|
|||
2) Original or Modified Versions of the Font Software may be bundled, |
|||
redistributed and/or sold with any software, provided that each copy |
|||
contains the above copyright notice and this license. These can be |
|||
included either as stand-alone text files, human-readable headers or |
|||
in the appropriate machine-readable metadata fields within text or |
|||
binary files as long as those fields can be easily viewed by the user. |
|||
|
|||
3) No Modified Version of the Font Software may use the Reserved Font |
|||
Name(s) unless explicit written permission is granted by the corresponding |
|||
Copyright Holder. This restriction only applies to the primary font name as |
|||
presented to the users. |
|||
|
|||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font |
|||
Software shall not be used to promote, endorse or advertise any |
|||
Modified Version, except to acknowledge the contribution(s) of the |
|||
Copyright Holder(s) and the Author(s) or with their explicit written |
|||
permission. |
|||
|
|||
5) The Font Software, modified or unmodified, in part or in whole, |
|||
must be distributed entirely under this license, and must not be |
|||
distributed under any other license. The requirement for fonts to |
|||
remain under this license does not apply to any document created |
|||
using the Font Software. |
|||
|
|||
TERMINATION |
|||
This license becomes null and void if any of the above conditions are |
|||
not met. |
|||
|
|||
DISCLAIMER |
|||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
|||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF |
|||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT |
|||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE |
|||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, |
|||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL |
|||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
|||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM |
|||
OTHER DEALINGS IN THE FONT SOFTWARE. |
|||
@ -0,0 +1,21 @@ |
|||
The MIT License (MIT) |
|||
|
|||
Copyright (c) 2014 Waybury |
|||
|
|||
Permission is hereby granted, free of charge, to any person obtaining a copy |
|||
of this software and associated documentation files (the "Software"), to deal |
|||
in the Software without restriction, including without limitation the rights |
|||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
|||
copies of the Software, and to permit persons to whom the Software is |
|||
furnished to do so, subject to the following conditions: |
|||
|
|||
The above copyright notice and this permission notice shall be included in |
|||
all copies or substantial portions of the Software. |
|||
|
|||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|||
THE SOFTWARE. |
|||
@ -0,0 +1,114 @@ |
|||
[Open Iconic v1.1.1](http://useiconic.com/open) |
|||
=========== |
|||
|
|||
### Open Iconic is the open source sibling of [Iconic](http://useiconic.com). It is a hyper-legible collection of 223 icons with a tiny footprint—ready to use with Bootstrap and Foundation. [View the collection](http://useiconic.com/open#icons) |
|||
|
|||
|
|||
|
|||
## What's in Open Iconic? |
|||
|
|||
* 223 icons designed to be legible down to 8 pixels |
|||
* Super-light SVG files - 61.8 for the entire set |
|||
* SVG sprite—the modern replacement for icon fonts |
|||
* Webfont (EOT, OTF, SVG, TTF, WOFF), PNG and WebP formats |
|||
* Webfont stylesheets (including versions for Bootstrap and Foundation) in CSS, LESS, SCSS and Stylus formats |
|||
* PNG and WebP raster images in 8px, 16px, 24px, 32px, 48px and 64px. |
|||
|
|||
|
|||
## Getting Started |
|||
|
|||
#### For code samples and everything else you need to get started with Open Iconic, check out our [Icons](http://useiconic.com/open#icons) and [Reference](http://useiconic.com/open#reference) sections. |
|||
|
|||
### General Usage |
|||
|
|||
#### Using Open Iconic's SVGs |
|||
|
|||
We like SVGs and we think they're the way to display icons on the web. Since Open Iconic are just basic SVGs, we suggest you display them like you would any other image (don't forget the `alt` attribute). |
|||
|
|||
``` |
|||
<img src="/open-iconic/svg/icon-name.svg" alt="icon name"> |
|||
``` |
|||
|
|||
#### Using Open Iconic's SVG Sprite |
|||
|
|||
Open Iconic also comes in a SVG sprite which allows you to display all the icons in the set with a single request. It's like an icon font, without being a hack. |
|||
|
|||
Adding an icon from an SVG sprite is a little different than what you're used to, but it's still a piece of cake. *Tip: To make your icons easily style able, we suggest adding a general class to the* `<svg>` *tag and a unique class name for each different icon in the* `<use>` *tag.* |
|||
|
|||
``` |
|||
<svg class="icon"> |
|||
<use xlink:href="open-iconic.svg#account-login" class="icon-account-login"></use> |
|||
</svg> |
|||
``` |
|||
|
|||
Sizing icons only needs basic CSS. All the icons are in a square format, so just set the `<svg>` tag with equal width and height dimensions. |
|||
|
|||
``` |
|||
.icon { |
|||
width: 16px; |
|||
height: 16px; |
|||
} |
|||
``` |
|||
|
|||
Coloring icons is even easier. All you need to do is set the `fill` rule on the `<use>` tag. |
|||
|
|||
``` |
|||
.icon-account-login { |
|||
fill: #f00; |
|||
} |
|||
``` |
|||
|
|||
To learn more about SVG Sprites, read [Chris Coyier's guide](http://css-tricks.com/svg-sprites-use-better-icon-fonts/). |
|||
|
|||
#### Using Open Iconic's Icon Font... |
|||
|
|||
|
|||
##### …with Bootstrap |
|||
|
|||
You can find our Bootstrap stylesheets in `font/css/open-iconic-bootstrap.{css, less, scss, styl}` |
|||
|
|||
|
|||
``` |
|||
<link href="/open-iconic/font/css/open-iconic-bootstrap.css" rel="stylesheet"> |
|||
``` |
|||
|
|||
|
|||
``` |
|||
<span class="oi oi-icon-name" title="icon name" aria-hidden="true"></span> |
|||
``` |
|||
|
|||
##### …with Foundation |
|||
|
|||
You can find our Foundation stylesheets in `font/css/open-iconic-foundation.{css, less, scss, styl}` |
|||
|
|||
``` |
|||
<link href="/open-iconic/font/css/open-iconic-foundation.css" rel="stylesheet"> |
|||
``` |
|||
|
|||
|
|||
``` |
|||
<span class="fi-icon-name" title="icon name" aria-hidden="true"></span> |
|||
``` |
|||
|
|||
##### …on its own |
|||
|
|||
You can find our default stylesheets in `font/css/open-iconic.{css, less, scss, styl}` |
|||
|
|||
``` |
|||
<link href="/open-iconic/font/css/open-iconic.css" rel="stylesheet"> |
|||
``` |
|||
|
|||
``` |
|||
<span class="oi" data-glyph="icon-name" title="icon name" aria-hidden="true"></span> |
|||
``` |
|||
|
|||
|
|||
## License |
|||
|
|||
### Icons |
|||
|
|||
All code (including SVG markup) is under the [MIT License](http://opensource.org/licenses/MIT). |
|||
|
|||
### Fonts |
|||
|
|||
All fonts are under the [SIL Licensed](http://scripts.sil.org/cms/scripts/page.php?item_id=OFL_web). |
|||
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 54 KiB |
Binary file not shown.
Binary file not shown.
@ -0,0 +1,183 @@ |
|||
@import url('open-iconic/font/css/open-iconic-bootstrap.min.css'); |
|||
|
|||
html, body { |
|||
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; |
|||
} |
|||
|
|||
a, .btn-link { |
|||
color: #0366d6; |
|||
} |
|||
|
|||
.btn-primary { |
|||
color: #fff; |
|||
background-color: #1b6ec2; |
|||
border-color: #1861ac; |
|||
} |
|||
|
|||
app { |
|||
position: relative; |
|||
display: flex; |
|||
flex-direction: column; |
|||
} |
|||
|
|||
.top-row { |
|||
height: 3.5rem; |
|||
display: flex; |
|||
align-items: center; |
|||
} |
|||
|
|||
.main { |
|||
flex: 1; |
|||
} |
|||
|
|||
.main .top-row { |
|||
background-color: #f7f7f7; |
|||
border-bottom: 1px solid #d6d5d5; |
|||
justify-content: flex-end; |
|||
} |
|||
|
|||
.main .top-row > a, .main .top-row .btn-link { |
|||
white-space: nowrap; |
|||
margin-left: 1.5rem; |
|||
} |
|||
|
|||
.main .top-row a:first-child { |
|||
overflow: hidden; |
|||
text-overflow: ellipsis; |
|||
} |
|||
|
|||
.sidebar { |
|||
background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); |
|||
} |
|||
|
|||
.sidebar .top-row { |
|||
background-color: rgba(0,0,0,0.4); |
|||
} |
|||
|
|||
.sidebar .navbar-brand { |
|||
font-size: 1.1rem; |
|||
} |
|||
|
|||
.sidebar .oi { |
|||
width: 2rem; |
|||
font-size: 1.1rem; |
|||
vertical-align: text-top; |
|||
top: -2px; |
|||
} |
|||
|
|||
.sidebar .nav-item { |
|||
font-size: 0.9rem; |
|||
padding-bottom: 0.5rem; |
|||
} |
|||
|
|||
.sidebar .nav-item:first-of-type { |
|||
padding-top: 1rem; |
|||
} |
|||
|
|||
.sidebar .nav-item:last-of-type { |
|||
padding-bottom: 1rem; |
|||
} |
|||
|
|||
.sidebar .nav-item a { |
|||
color: #d7d7d7; |
|||
border-radius: 4px; |
|||
height: 3rem; |
|||
display: flex; |
|||
align-items: center; |
|||
line-height: 3rem; |
|||
} |
|||
|
|||
.sidebar .nav-item a.active { |
|||
background-color: rgba(255,255,255,0.25); |
|||
color: white; |
|||
} |
|||
|
|||
.sidebar .nav-item a:hover { |
|||
background-color: rgba(255,255,255,0.1); |
|||
color: white; |
|||
} |
|||
|
|||
.content { |
|||
padding-top: 1.1rem; |
|||
} |
|||
|
|||
.navbar-toggler { |
|||
background-color: rgba(255, 255, 255, 0.1); |
|||
} |
|||
|
|||
.valid.modified:not([type=checkbox]) { |
|||
outline: 1px solid #26b050; |
|||
} |
|||
|
|||
.invalid { |
|||
outline: 1px solid red; |
|||
} |
|||
|
|||
.validation-message { |
|||
color: red; |
|||
} |
|||
|
|||
#blazor-error-ui { |
|||
background: lightyellow; |
|||
bottom: 0; |
|||
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); |
|||
display: none; |
|||
left: 0; |
|||
padding: 0.6rem 1.25rem 0.7rem 1.25rem; |
|||
position: fixed; |
|||
width: 100%; |
|||
z-index: 1000; |
|||
} |
|||
|
|||
#blazor-error-ui .dismiss { |
|||
cursor: pointer; |
|||
position: absolute; |
|||
right: 0.75rem; |
|||
top: 0.5rem; |
|||
} |
|||
|
|||
@media (max-width: 767.98px) { |
|||
.main .top-row:not(.auth) { |
|||
display: none; |
|||
} |
|||
|
|||
.main .top-row.auth { |
|||
justify-content: space-between; |
|||
} |
|||
|
|||
.main .top-row a, .main .top-row .btn-link { |
|||
margin-left: 0; |
|||
} |
|||
} |
|||
|
|||
@media (min-width: 768px) { |
|||
app { |
|||
flex-direction: row; |
|||
} |
|||
|
|||
.sidebar { |
|||
width: 250px; |
|||
height: 100vh; |
|||
position: sticky; |
|||
top: 0; |
|||
} |
|||
|
|||
.main .top-row { |
|||
position: sticky; |
|||
top: 0; |
|||
} |
|||
|
|||
.main > div { |
|||
padding-left: 2rem !important; |
|||
padding-right: 1.5rem !important; |
|||
} |
|||
|
|||
.navbar-toggler { |
|||
display: none; |
|||
} |
|||
|
|||
.sidebar .collapse { |
|||
/* Never collapse the sidebar for wide screens */ |
|||
display: block; |
|||
} |
|||
} |
|||
|
After Width: | Height: | Size: 31 KiB |
@ -0,0 +1,20 @@ |
|||
name: VotingSample |
|||
services: |
|||
- name: vote |
|||
project: vote/vote.csproj |
|||
- name: worker |
|||
azureFunction: worker-function/ |
|||
- name: azure-storage |
|||
external: true |
|||
bindings: |
|||
- connectionString: "UseDevelopmentStorage=true" |
|||
- name: postgres |
|||
image: postgres |
|||
env: |
|||
- name: POSTGRES_PASSWORD |
|||
value: "pass@word1" |
|||
bindings: |
|||
- port: 5432 |
|||
connectionString: Server=${host};Port=${port};User Id=postgres;Password=${env:POSTGRES_PASSWORD}; |
|||
- name: results |
|||
project: results/results.csproj |
|||
@ -0,0 +1,60 @@ |
|||
@page |
|||
@model IndexModel |
|||
@using Microsoft.Extensions.Hosting; |
|||
@inject IHostEnvironment env |
|||
|
|||
<!DOCTYPE html> |
|||
<html lang="en"> |
|||
<head> |
|||
@if(!env.IsDevelopment()) |
|||
{ |
|||
<base href="/vote/" > |
|||
} |
|||
<meta charset="utf-8" /> |
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
|||
<title>@Model.Configuration["OptionA"] vs @Model.Configuration["OptionB"]</title> |
|||
<link rel="stylesheet" href="site.css" /> |
|||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> |
|||
</head> |
|||
<body> |
|||
<header> |
|||
</header> |
|||
|
|||
<div id="content-container"> |
|||
<div id="content-container-center"> |
|||
<h3>@Model.Configuration["OptionA"] vs @Model.Configuration["OptionB"]!</h3> |
|||
<form id="choice" name='form' method="POST"> |
|||
<button id="a" type="submit" name="vote" class="a" value="a" disabled=@(Model.Vote == "a" ? "disabled" : null) style=@(Model.Vote == "a" ? "opacity:0.5;" : null)> |
|||
@if (Model.Vote == "a") |
|||
{ |
|||
<i class="fa fa-check-circle"></i> |
|||
} |
|||
@Model.Configuration["OptionA"] |
|||
</button> |
|||
<button id="b" type="submit" name="vote" class="b" value="b" disabled=@(Model.Vote == "b" ? "disabled" : null) style=@(Model.Vote == "b" ? "opacity:0.5;" : null)> |
|||
@if (Model.Vote == "b") |
|||
{ |
|||
<i class="fa fa-check-circle"></i> |
|||
} |
|||
@Model.Configuration["OptionB"] |
|||
</button> |
|||
</form> |
|||
<div id="tip"> |
|||
(Tip: you can change your vote) |
|||
</div> |
|||
<div id="hostname"> |
|||
Processed by container ID @Environment.MachineName |
|||
</div> |
|||
</div> |
|||
</div> |
|||
|
|||
<footer class="footer"> |
|||
<div class="container-content-center"> |
|||
<span class="text-nowrap"> |
|||
Like Tye? Please take our <a target="_blank" class="font-weight-bold" href="https://go.microsoft.com/fwlink/?linkid=2116045">brief survey</a> and tell us what you think. |
|||
</span> |
|||
</div> |
|||
</footer> |
|||
|
|||
</body> |
|||
</html> |
|||
@ -0,0 +1,55 @@ |
|||
using System; |
|||
using System.Text.Json; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Mvc; |
|||
using Microsoft.AspNetCore.Mvc.RazorPages; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Extensions.Logging; |
|||
using Azure.Storage.Queues; // Namespace for Queue storage types
|
|||
using Azure.Storage.Queues.Models; // Namespace for PeekedMessage
|
|||
using System.Text; |
|||
|
|||
namespace Vote.Pages |
|||
{ |
|||
public class IndexModel : PageModel |
|||
{ |
|||
private readonly ILogger<IndexModel> _logger; |
|||
public IConfiguration Configuration { get; set; } |
|||
|
|||
[BindProperty()] |
|||
public string Vote {get;set;} |
|||
|
|||
public IndexModel(ILogger<IndexModel> logger, IConfiguration configuration) |
|||
{ |
|||
_logger = logger; |
|||
Configuration = configuration; |
|||
} |
|||
|
|||
public async Task OnPost() |
|||
{ |
|||
try |
|||
{ |
|||
var voterId = TempData.Peek("VoterId"); |
|||
if (voterId == null) |
|||
{ |
|||
voterId = Guid.NewGuid(); |
|||
TempData["VoterId"] = voterId; |
|||
} |
|||
|
|||
var data = JsonSerializer.Serialize(new { voterId = voterId, vote = Vote }); |
|||
|
|||
_logger.LogInformation($"pushing {data}"); |
|||
|
|||
var plainTextBytes = Encoding.UTF8.GetBytes(data); |
|||
|
|||
QueueClient queueClient = new QueueClient(Configuration.GetConnectionString("azure-storage"), "test-queue"); |
|||
queueClient.CreateIfNotExists(); |
|||
await queueClient.SendMessageAsync(Convert.ToBase64String(plainTextBytes)); |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
_logger.LogError(ex, "Error submitting vote."); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,4 @@ |
|||
@using Vote |
|||
@using Microsoft.Extensions.Configuration |
|||
@namespace Vote.Pages |
|||
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers |
|||
@ -0,0 +1,34 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.IO; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Extensions.Hosting; |
|||
using Microsoft.Extensions.Logging; |
|||
|
|||
namespace Vote |
|||
{ |
|||
public class Program |
|||
{ |
|||
public static void Main(string[] args) |
|||
{ |
|||
try |
|||
{ |
|||
CreateHostBuilder(args).Build().Run(); |
|||
} |
|||
catch (Exception x) |
|||
{ |
|||
Console.WriteLine(x.Message); |
|||
} |
|||
} |
|||
|
|||
public static IHostBuilder CreateHostBuilder(string[] args) => |
|||
Host.CreateDefaultBuilder(args) |
|||
.ConfigureWebHostDefaults(webBuilder => |
|||
{ |
|||
webBuilder.UseStartup<Startup>(); |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
{ |
|||
"iisSettings": { |
|||
"windowsAuthentication": false, |
|||
"anonymousAuthentication": true, |
|||
"iisExpress": { |
|||
"applicationUrl": "http://localhost:14422", |
|||
"sslPort": 44382 |
|||
} |
|||
}, |
|||
"profiles": { |
|||
"IIS Express": { |
|||
"commandName": "IISExpress", |
|||
"launchBrowser": true, |
|||
"environmentVariables": { |
|||
"ASPNETCORE_ENVIRONMENT": "Development" |
|||
} |
|||
}, |
|||
"vote": { |
|||
"commandName": "Project", |
|||
"launchBrowser": true, |
|||
"applicationUrl": "https://localhost:5006;http://localhost:5007", |
|||
"environmentVariables": { |
|||
"ASPNETCORE_ENVIRONMENT": "Development" |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,50 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Builder; |
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.AspNetCore.HttpsPolicy; |
|||
using Microsoft.AspNetCore.Mvc; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Hosting; |
|||
|
|||
namespace Vote |
|||
{ |
|||
public class Startup |
|||
{ |
|||
public Startup(IConfiguration configuration) |
|||
{ |
|||
Configuration = configuration; |
|||
} |
|||
|
|||
public IConfiguration Configuration { get; } |
|||
|
|||
// This method gets called by the runtime. Use this method to add services to the container.
|
|||
public void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
services.AddRazorPages(); |
|||
} |
|||
|
|||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
|||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) |
|||
{ |
|||
if (env.IsDevelopment()) |
|||
{ |
|||
app.UseDeveloperExceptionPage(); |
|||
} |
|||
|
|||
app.UseStaticFiles(); |
|||
|
|||
app.UseRouting(); |
|||
|
|||
app.UseAuthorization(); |
|||
|
|||
app.UseEndpoints(endpoints => |
|||
{ |
|||
endpoints.MapRazorPages(); |
|||
}); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Logging": { |
|||
"LogLevel": { |
|||
"Default": "Information", |
|||
"Microsoft": "Information", |
|||
"Microsoft.Hosting.Lifetime": "Information" |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,12 @@ |
|||
{ |
|||
"Logging": { |
|||
"LogLevel": { |
|||
"Default": "Information", |
|||
"Microsoft": "Information", |
|||
"Microsoft.Hosting.Lifetime": "Information" |
|||
} |
|||
}, |
|||
"AllowedHosts": "*", |
|||
"OptionA": "Dogs", |
|||
"OptionB": "Cats" |
|||
} |
|||
@ -0,0 +1,16 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk.Web"> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>netcoreapp3.1</TargetFramework> |
|||
<RootNamespace>Vote</RootNamespace> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="$(TyeLibrariesPath)\Microsoft.Tye.Extensions.Configuration\Microsoft.Tye.Extensions.Configuration.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Azure.Storage.Queues" Version="12.3.2" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
|
After Width: | Height: | Size: 31 KiB |
@ -0,0 +1,129 @@ |
|||
@import url(//fonts.googleapis.com/css?family=Open+Sans:400,700,600); |
|||
|
|||
*{ |
|||
box-sizing:border-box; |
|||
} |
|||
html,body{ |
|||
margin: 0; |
|||
padding: 0; |
|||
background-color: #F7F8F9; |
|||
height: 100vh; |
|||
font-family: 'Open Sans'; |
|||
} |
|||
|
|||
button{ |
|||
border-radius: 0; |
|||
width: 100%; |
|||
height: 50%; |
|||
} |
|||
|
|||
button[type="submit"] { |
|||
-webkit-appearance:none; -webkit-border-radius:0; |
|||
} |
|||
|
|||
button i{ |
|||
float: right; |
|||
padding-right: 30px; |
|||
margin-top: 3px; |
|||
} |
|||
|
|||
button.a{ |
|||
background-color: #1aaaf8; |
|||
} |
|||
|
|||
button.b{ |
|||
background-color: #00cbca; |
|||
} |
|||
|
|||
#tip{ |
|||
text-align: left; |
|||
color: #c0c9ce; |
|||
font-size: 14px; |
|||
} |
|||
|
|||
#hostname{ |
|||
position: absolute; |
|||
bottom: 100px; |
|||
right: 0; |
|||
left: 0; |
|||
color: #8f9ea8; |
|||
font-size: 24px; |
|||
} |
|||
|
|||
#content-container{ |
|||
z-index: 2; |
|||
position: relative; |
|||
margin: 0 auto; |
|||
display: table; |
|||
padding: 10px; |
|||
max-width: 940px; |
|||
height: 100%; |
|||
} |
|||
#content-container-center{ |
|||
display: table-cell; |
|||
text-align: center; |
|||
} |
|||
|
|||
#content-container-center h3{ |
|||
color: #254356; |
|||
} |
|||
|
|||
#choice{ |
|||
transition: all 300ms linear; |
|||
line-height: 1.3em; |
|||
display: inline; |
|||
vertical-align: middle; |
|||
font-size: 3em; |
|||
} |
|||
#choice a{ |
|||
text-decoration:none; |
|||
} |
|||
#choice a:hover, #choice a:focus{ |
|||
outline:0; |
|||
text-decoration:underline; |
|||
} |
|||
|
|||
#choice button{ |
|||
display: block; |
|||
height: 80px; |
|||
width: 330px; |
|||
border: none; |
|||
color: white; |
|||
text-transform: uppercase; |
|||
font-size:18px; |
|||
font-weight: 700; |
|||
margin-top: 10px; |
|||
margin-bottom: 10px; |
|||
text-align: left; |
|||
padding-left: 50px; |
|||
} |
|||
|
|||
#choice button.a:hover{ |
|||
background-color: #1488c6; |
|||
} |
|||
|
|||
#choice button.b:hover{ |
|||
background-color: #00a2a1; |
|||
} |
|||
|
|||
#choice button.a:focus{ |
|||
background-color: #1488c6; |
|||
} |
|||
|
|||
#choice button.b:focus{ |
|||
background-color: #00a2a1; |
|||
} |
|||
|
|||
#background-stats{ |
|||
z-index:1; |
|||
height:100%; |
|||
width:100%; |
|||
position:absolute; |
|||
} |
|||
#background-stats div{ |
|||
transition: width 400ms ease-in-out; |
|||
display:inline-block; |
|||
margin-bottom:-4px; |
|||
width:50%; |
|||
height:100%; |
|||
} |
|||
@ -0,0 +1,264 @@ |
|||
## Ignore Visual Studio temporary files, build results, and |
|||
## files generated by popular Visual Studio add-ons. |
|||
|
|||
# Azure Functions localsettings file |
|||
local.settings.json |
|||
|
|||
# User-specific files |
|||
*.suo |
|||
*.user |
|||
*.userosscache |
|||
*.sln.docstates |
|||
|
|||
# User-specific files (MonoDevelop/Xamarin Studio) |
|||
*.userprefs |
|||
|
|||
# Build results |
|||
[Dd]ebug/ |
|||
[Dd]ebugPublic/ |
|||
[Rr]elease/ |
|||
[Rr]eleases/ |
|||
x64/ |
|||
x86/ |
|||
bld/ |
|||
[Bb]in/ |
|||
[Oo]bj/ |
|||
[Ll]og/ |
|||
|
|||
# Visual Studio 2015 cache/options directory |
|||
.vs/ |
|||
# Uncomment if you have tasks that create the project's static files in wwwroot |
|||
#wwwroot/ |
|||
|
|||
# MSTest test Results |
|||
[Tt]est[Rr]esult*/ |
|||
[Bb]uild[Ll]og.* |
|||
|
|||
# NUNIT |
|||
*.VisualState.xml |
|||
TestResult.xml |
|||
|
|||
# Build Results of an ATL Project |
|||
[Dd]ebugPS/ |
|||
[Rr]eleasePS/ |
|||
dlldata.c |
|||
|
|||
# DNX |
|||
project.lock.json |
|||
project.fragment.lock.json |
|||
artifacts/ |
|||
|
|||
*_i.c |
|||
*_p.c |
|||
*_i.h |
|||
*.ilk |
|||
*.meta |
|||
*.obj |
|||
*.pch |
|||
*.pdb |
|||
*.pgc |
|||
*.pgd |
|||
*.rsp |
|||
*.sbr |
|||
*.tlb |
|||
*.tli |
|||
*.tlh |
|||
*.tmp |
|||
*.tmp_proj |
|||
*.log |
|||
*.vspscc |
|||
*.vssscc |
|||
.builds |
|||
*.pidb |
|||
*.svclog |
|||
*.scc |
|||
|
|||
# Chutzpah Test files |
|||
_Chutzpah* |
|||
|
|||
# Visual C++ cache files |
|||
ipch/ |
|||
*.aps |
|||
*.ncb |
|||
*.opendb |
|||
*.opensdf |
|||
*.sdf |
|||
*.cachefile |
|||
*.VC.db |
|||
*.VC.VC.opendb |
|||
|
|||
# Visual Studio profiler |
|||
*.psess |
|||
*.vsp |
|||
*.vspx |
|||
*.sap |
|||
|
|||
# TFS 2012 Local Workspace |
|||
$tf/ |
|||
|
|||
# Guidance Automation Toolkit |
|||
*.gpState |
|||
|
|||
# ReSharper is a .NET coding add-in |
|||
_ReSharper*/ |
|||
*.[Rr]e[Ss]harper |
|||
*.DotSettings.user |
|||
|
|||
# JustCode is a .NET coding add-in |
|||
.JustCode |
|||
|
|||
# TeamCity is a build add-in |
|||
_TeamCity* |
|||
|
|||
# DotCover is a Code Coverage Tool |
|||
*.dotCover |
|||
|
|||
# NCrunch |
|||
_NCrunch_* |
|||
.*crunch*.local.xml |
|||
nCrunchTemp_* |
|||
|
|||
# MightyMoose |
|||
*.mm.* |
|||
AutoTest.Net/ |
|||
|
|||
# Web workbench (sass) |
|||
.sass-cache/ |
|||
|
|||
# Installshield output folder |
|||
[Ee]xpress/ |
|||
|
|||
# DocProject is a documentation generator add-in |
|||
DocProject/buildhelp/ |
|||
DocProject/Help/*.HxT |
|||
DocProject/Help/*.HxC |
|||
DocProject/Help/*.hhc |
|||
DocProject/Help/*.hhk |
|||
DocProject/Help/*.hhp |
|||
DocProject/Help/Html2 |
|||
DocProject/Help/html |
|||
|
|||
# Click-Once directory |
|||
publish/ |
|||
|
|||
# Publish Web Output |
|||
*.[Pp]ublish.xml |
|||
*.azurePubxml |
|||
# TODO: Comment the next line if you want to checkin your web deploy settings |
|||
# but database connection strings (with potential passwords) will be unencrypted |
|||
#*.pubxml |
|||
*.publishproj |
|||
|
|||
# Microsoft Azure Web App publish settings. Comment the next line if you want to |
|||
# checkin your Azure Web App publish settings, but sensitive information contained |
|||
# in these scripts will be unencrypted |
|||
PublishScripts/ |
|||
|
|||
# NuGet Packages |
|||
*.nupkg |
|||
# The packages folder can be ignored because of Package Restore |
|||
**/packages/* |
|||
# except build/, which is used as an MSBuild target. |
|||
!**/packages/build/ |
|||
# Uncomment if necessary however generally it will be regenerated when needed |
|||
#!**/packages/repositories.config |
|||
# NuGet v3's project.json files produces more ignoreable files |
|||
*.nuget.props |
|||
*.nuget.targets |
|||
|
|||
# Microsoft Azure Build Output |
|||
csx/ |
|||
*.build.csdef |
|||
|
|||
# Microsoft Azure Emulator |
|||
ecf/ |
|||
rcf/ |
|||
|
|||
# Windows Store app package directories and files |
|||
AppPackages/ |
|||
BundleArtifacts/ |
|||
Package.StoreAssociation.xml |
|||
_pkginfo.txt |
|||
|
|||
# Visual Studio cache files |
|||
# files ending in .cache can be ignored |
|||
*.[Cc]ache |
|||
# but keep track of directories ending in .cache |
|||
!*.[Cc]ache/ |
|||
|
|||
# Others |
|||
ClientBin/ |
|||
~$* |
|||
*~ |
|||
*.dbmdl |
|||
*.dbproj.schemaview |
|||
*.jfm |
|||
*.pfx |
|||
*.publishsettings |
|||
node_modules/ |
|||
orleans.codegen.cs |
|||
|
|||
# Since there are multiple workflows, uncomment next line to ignore bower_components |
|||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) |
|||
#bower_components/ |
|||
|
|||
# RIA/Silverlight projects |
|||
Generated_Code/ |
|||
|
|||
# Backup & report files from converting an old project file |
|||
# to a newer Visual Studio version. Backup files are not needed, |
|||
# because we have git ;-) |
|||
_UpgradeReport_Files/ |
|||
Backup*/ |
|||
UpgradeLog*.XML |
|||
UpgradeLog*.htm |
|||
|
|||
# SQL Server files |
|||
*.mdf |
|||
*.ldf |
|||
|
|||
# Business Intelligence projects |
|||
*.rdl.data |
|||
*.bim.layout |
|||
*.bim_*.settings |
|||
|
|||
# Microsoft Fakes |
|||
FakesAssemblies/ |
|||
|
|||
# GhostDoc plugin setting file |
|||
*.GhostDoc.xml |
|||
|
|||
# Node.js Tools for Visual Studio |
|||
.ntvs_analysis.dat |
|||
|
|||
# Visual Studio 6 build log |
|||
*.plg |
|||
|
|||
# Visual Studio 6 workspace options file |
|||
*.opt |
|||
|
|||
# Visual Studio LightSwitch build output |
|||
**/*.HTMLClient/GeneratedArtifacts |
|||
**/*.DesktopClient/GeneratedArtifacts |
|||
**/*.DesktopClient/ModelManifest.xml |
|||
**/*.Server/GeneratedArtifacts |
|||
**/*.Server/ModelManifest.xml |
|||
_Pvt_Extensions |
|||
|
|||
# Paket dependency manager |
|||
.paket/paket.exe |
|||
paket-files/ |
|||
|
|||
# FAKE - F# Make |
|||
.fake/ |
|||
|
|||
# JetBrains Rider |
|||
.idea/ |
|||
*.sln.iml |
|||
|
|||
# CodeRush |
|||
.cr/ |
|||
|
|||
# Python Tools for Visual Studio (PTVS) |
|||
__pycache__/ |
|||
*.pyc |
|||
@ -0,0 +1,14 @@ |
|||
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS installer-env |
|||
|
|||
COPY . /src/dotnet-function-app |
|||
RUN cd /src/dotnet-function-app && \ |
|||
mkdir -p /home/site/wwwroot && \ |
|||
dotnet publish *.csproj --output /home/site/wwwroot |
|||
|
|||
# To enable ssh & remote debugging on app service change the base image to the one below |
|||
# FROM mcr.microsoft.com/azure-functions/dotnet:3.0-appservice |
|||
FROM mcr.microsoft.com/azure-functions/dotnet:3.0 |
|||
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \ |
|||
AzureFunctionsJobHost__Logging__Console__IsEnabled=true |
|||
|
|||
COPY --from=installer-env ["/home/site/wwwroot", "/home/site/wwwroot"] |
|||
@ -0,0 +1,38 @@ |
|||
using System; |
|||
using System.IO; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Mvc; |
|||
using Microsoft.Azure.WebJobs; |
|||
using Microsoft.Azure.WebJobs.Extensions.Http; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Npgsql; |
|||
using Dapper; |
|||
using System.Text.Json; |
|||
|
|||
namespace worker_function |
|||
{ |
|||
public class GetResults |
|||
{ |
|||
private readonly IConfiguration _configuration; |
|||
|
|||
public GetResults(IConfiguration configuration) |
|||
{ |
|||
_configuration = configuration; |
|||
} |
|||
|
|||
[FunctionName("GetResults")] |
|||
public async Task<IActionResult> Run( |
|||
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, |
|||
ILogger log) |
|||
{ |
|||
log.LogInformation(_configuration.GetConnectionString("postgres")); |
|||
using (var connection = new NpgsqlConnection(_configuration.GetConnectionString("postgres"))) |
|||
{ |
|||
var newResults = await connection.QueryAsync<QueueTrigger.VoteCount>("SELECT Vote, COUNT(Id) AS Count FROM votes GROUP BY Vote ORDER BY Vote"); |
|||
return new OkObjectResult(JsonSerializer.Serialize(newResults)); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,57 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using System.Text.Json; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Azure.WebJobs; |
|||
using Microsoft.Azure.WebJobs.Host; |
|||
using Microsoft.Extensions.Logging; |
|||
using Dapper; |
|||
using Npgsql; |
|||
|
|||
namespace worker_function |
|||
{ |
|||
public class QueueTrigger |
|||
{ |
|||
private readonly IConfiguration _configuration; |
|||
|
|||
public QueueTrigger(IConfiguration configuration) |
|||
{ |
|||
_configuration = configuration; |
|||
} |
|||
|
|||
[FunctionName("QueueTrigger")] |
|||
public async Task Run([QueueTrigger("test-queue", Connection = "AzureWebJobsStorage")]string data, ILogger log) |
|||
{ |
|||
log.LogInformation(_configuration.GetConnectionString("postgres")); |
|||
using (var connection = new NpgsqlConnection(_configuration.GetConnectionString("postgres"))) |
|||
{ |
|||
var vote = JsonSerializer.Deserialize<Vote>(data); |
|||
// TODO
|
|||
connection.Open(); |
|||
await connection.ExecuteAsync(@"CREATE TABLE IF NOT EXISTS votes (
|
|||
Id VARCHAR(255) NOT NULL UNIQUE, |
|||
Vote VARCHAR(255) NOT NULL);");
|
|||
|
|||
var command = @"INSERT INTO votes (Id, Vote) VALUES (@voterId, @vote)
|
|||
ON CONFLICT (Id) |
|||
DO UPDATE SET Vote = @vote";
|
|||
|
|||
await connection.ExecuteAsync(command, vote); |
|||
} |
|||
|
|||
log.LogInformation($"C# Queue trigger function processed: {data}"); |
|||
} |
|||
|
|||
public class Vote |
|||
{ |
|||
public Guid voterId { get; set; } |
|||
public string vote { get; set; } |
|||
} |
|||
|
|||
public class VoteCount |
|||
{ |
|||
public string Vote { get; set; } |
|||
public int Count { get; set; } |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
using Microsoft.Azure.Functions.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
|
|||
[assembly: FunctionsStartup(typeof(worker_function.Startup))] |
|||
|
|||
namespace worker_function |
|||
{ |
|||
public class Startup : FunctionsStartup |
|||
{ |
|||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
|||
public override void Configure(IFunctionsHostBuilder builder) |
|||
{ |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
{ |
|||
"version": "2.0", |
|||
"logging": { |
|||
"applicationInsights": { |
|||
"samplingExcludedTypes": "Request", |
|||
"samplingSettings": { |
|||
"isEnabled": true |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,7 @@ |
|||
{ |
|||
"IsEncrypted": false, |
|||
"Values": { |
|||
"AzureWebJobsStorage": "UseDevelopmentStorage=true", |
|||
"FUNCTIONS_WORKER_RUNTIME": "dotnet" |
|||
} |
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
<PropertyGroup> |
|||
<TargetFramework>netcoreapp3.1</TargetFramework> |
|||
<AzureFunctionsVersion>v3</AzureFunctionsVersion> |
|||
<RootNamespace>worker_function</RootNamespace> |
|||
</PropertyGroup> |
|||
<ItemGroup> |
|||
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.10" /> |
|||
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" /> |
|||
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" /> |
|||
<PackageReference Include="dapper" Version="2.0.30" /> |
|||
<PackageReference Include="npgsql" Version="4.1.3.1" /> |
|||
</ItemGroup> |
|||
<ItemGroup> |
|||
<None Update="host.json"> |
|||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> |
|||
</None> |
|||
<None Update="local.settings.json"> |
|||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> |
|||
<CopyToPublishDirectory>Never</CopyToPublishDirectory> |
|||
</None> |
|||
</ItemGroup> |
|||
</Project> |
|||
@ -0,0 +1,22 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
namespace Microsoft.Tye |
|||
{ |
|||
public class AzureFunctionServiceBuilder : ServiceBuilder |
|||
{ |
|||
public AzureFunctionServiceBuilder(string name, string path) |
|||
: base(name) |
|||
{ |
|||
FunctionPath = path; |
|||
} |
|||
|
|||
public int Replicas { get; set; } = 1; |
|||
public string? Args { get; set; } |
|||
public string FunctionPath { get; } |
|||
public string? Version { get; set; } |
|||
public string? Architecture { get; set; } |
|||
public string? FuncExecutablePath { get; set; } |
|||
} |
|||
} |
|||
@ -0,0 +1,260 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.IO; |
|||
using System.IO.Compression; |
|||
using System.Linq; |
|||
using System.Net.Http; |
|||
using System.Runtime.InteropServices; |
|||
using System.Text; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Logging; |
|||
using Newtonsoft.Json; |
|||
using Newtonsoft.Json.Linq; |
|||
|
|||
namespace Microsoft.Tye |
|||
{ |
|||
public class FuncDetector |
|||
{ |
|||
// Same folder which VS installs azure apps to.
|
|||
private const string WindowsFuncDownloadLocation = "%LOCALAPPDATA%/AzureFunctionsTools/Tye"; |
|||
private string _macOSFuncDownloadLocation; |
|||
private string _linuxFuncDownloadLocation; |
|||
|
|||
// Default to v3 as it's highly backwards compatible with v2. Diagnostics with v2
|
|||
// don't work by default as v2 uses 2.2.
|
|||
private const string DefaultFuncVersion = "v3"; |
|||
|
|||
private Dictionary<string, string> _pathsToFunc; |
|||
|
|||
internal FuncDetector() |
|||
{ |
|||
_pathsToFunc = new Dictionary<string, string>(); |
|||
var baseDirectory = Environment.GetEnvironmentVariable("HOME") ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
|||
_macOSFuncDownloadLocation = Path.Combine(baseDirectory, ".tye/AzureFunctionTools/Tye"); |
|||
_linuxFuncDownloadLocation = Path.Combine(baseDirectory, ".tye/AzureFunctionTools/Tye"); |
|||
} |
|||
|
|||
public static FuncDetector Instance { get; } = new FuncDetector(); |
|||
|
|||
public async Task<string> PathToFunc(string? version, string? arch, string? downloadPath, ILogger logger, CancellationToken cancellation, bool dryRun = false) |
|||
{ |
|||
version = ValidateAndConvertVersion(version ?? DefaultFuncVersion, logger); |
|||
|
|||
// Default to x64
|
|||
arch = ValidateArch(arch ?? "x64"); |
|||
if (!_pathsToFunc.ContainsKey(version)) |
|||
{ |
|||
_pathsToFunc[version] = await GetPathToFunc(version, arch, downloadPath, logger, cancellation, dryRun); |
|||
} |
|||
|
|||
return _pathsToFunc[version]; |
|||
} |
|||
|
|||
private string ValidateArch(string arch) |
|||
{ |
|||
switch (arch) |
|||
{ |
|||
case "x64": |
|||
return arch; |
|||
case "x86": |
|||
return arch; |
|||
default: |
|||
throw new NotSupportedException("Unrecognized architecture for function."); |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Function to convert versions to versions expected.
|
|||
/// </summary>
|
|||
/// <param name="version"></param>
|
|||
/// <returns></returns>
|
|||
private string ValidateAndConvertVersion(string version, ILogger logger) |
|||
{ |
|||
switch (version) |
|||
{ |
|||
case "2": |
|||
case "v2": |
|||
return "v2"; |
|||
case "3": |
|||
case "v3": |
|||
return "v3"; |
|||
case "1": |
|||
case "v1": |
|||
// TODO maybe don't throw here and just log a warning.
|
|||
logger.LogWarning("Functions V1 are unsupported and untested in Tye. Use at your own risk!"); |
|||
return "v1"; |
|||
default: |
|||
return version; |
|||
} |
|||
} |
|||
|
|||
private async Task<string> GetPathToFunc(string version, string arch, string? downloadPath, ILogger logger, CancellationToken cancellation, bool dryRun) |
|||
{ |
|||
var osName = GetOsName(); |
|||
using var client = new HttpClient(); |
|||
|
|||
(var preciseVersion, var uri) = await GetDownloadInfo(version, client, arch, osName, logger, cancellation, dryRun); |
|||
|
|||
var directoryToInstallTo = downloadPath ?? GetAzureFunctionDirectoryWithVersion(preciseVersion); |
|||
|
|||
var funcPath = Path.Combine(directoryToInstallTo, GetFuncName()); |
|||
|
|||
if (Directory.Exists(directoryToInstallTo) && File.Exists(funcPath)) |
|||
{ |
|||
logger.LogInformation("Using func to {FuncPath}", funcPath); |
|||
return funcPath; |
|||
} |
|||
|
|||
var response = await client.GetAsync(uri); |
|||
|
|||
if (dryRun) |
|||
{ |
|||
return funcPath; |
|||
} |
|||
|
|||
using (var tempFile = TempFile.Create()) |
|||
{ |
|||
{ |
|||
var responseStream = await response.Content.ReadAsStreamAsync(); |
|||
await using var stream = File.OpenWrite(tempFile.FilePath); |
|||
await using var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), leaveOpen: true); |
|||
await responseStream.CopyToAsync(stream); |
|||
} |
|||
|
|||
logger.LogInformation("Installing func to {FuncPath}", directoryToInstallTo); |
|||
ZipFile.ExtractToDirectory(tempFile.FilePath, directoryToInstallTo); |
|||
// For some reason, func isn't marked as executable via unzipping.
|
|||
return funcPath; |
|||
} |
|||
} |
|||
|
|||
private async Task<(string, string)> GetDownloadInfo(string version, HttpClient client, string arch, string os, ILogger logger, CancellationToken cancellation, bool dryRun) |
|||
{ |
|||
var directory = GetAzureFunctionDirectory(); |
|||
|
|||
var feedJsonFile = Path.Combine(GetAzureFunctionDirectory(), "feed-v3.json"); |
|||
|
|||
JToken json; |
|||
if (File.Exists(feedJsonFile) && (DateTime.Now - File.GetLastWriteTimeUtc(feedJsonFile)).TotalDays < 90) |
|||
{ |
|||
logger.LogInformation("Using existing feed file in {FeedJsonFile}", feedJsonFile); |
|||
// don't bother rewriting it.
|
|||
using (JsonTextReader reader = new JsonTextReader(new StreamReader(feedJsonFile))) |
|||
{ |
|||
json = JObject.ReadFrom(reader); |
|||
} |
|||
} |
|||
else |
|||
{ |
|||
// Using VS/VSCode maintained list of function downloads
|
|||
logger.LogInformation("Retrieving list of azure function versions from internet."); |
|||
var response = await client.GetAsync("https://go.microsoft.com/fwlink/?linkid=2109029", cancellation); |
|||
|
|||
var responseString = await response.Content.ReadAsStringAsync(); |
|||
using (JsonTextReader reader = new JsonTextReader(new StringReader(responseString))) |
|||
{ |
|||
json = JObject.ReadFrom(reader); |
|||
} |
|||
|
|||
// Don't write file during dry run.
|
|||
if (!dryRun) |
|||
{ |
|||
logger.LogInformation("Writing list of azure function versions to {FeedJsonFile}.", feedJsonFile); |
|||
Directory.CreateDirectory(new FileInfo(feedJsonFile).DirectoryName); |
|||
await File.WriteAllTextAsync(feedJsonFile, responseString, cancellation); |
|||
} |
|||
} |
|||
|
|||
// Get the version for the folder
|
|||
// and the download link for the zip.
|
|||
var versionInfo = (JValue)json["tags"][version]["release"]; |
|||
JValue? downloadLink; |
|||
if (version == "v1") |
|||
{ |
|||
downloadLink = (JValue)json["releases"][(string)versionInfo]["cli"]; |
|||
} |
|||
else |
|||
{ |
|||
downloadLink = (JValue)json["releases"][(string)versionInfo]["standaloneCli"] |
|||
.Where(s => (((string)s["OS"])?.Equals(os) == true || ((string)s["OperatingSystem"])?.Equals(os) == true) && ((string)s["Architecture"]).Equals(arch)) |
|||
.Single()["downloadLink"]; |
|||
} |
|||
|
|||
return ((string)versionInfo, (string)downloadLink); |
|||
} |
|||
|
|||
|
|||
public string GetAzureFunctionDirectory() |
|||
{ |
|||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
|||
{ |
|||
// Default is min.win for whatever reason, probably minified win
|
|||
return Environment.ExpandEnvironmentVariables(WindowsFuncDownloadLocation); |
|||
} |
|||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
|||
{ |
|||
return Environment.ExpandEnvironmentVariables(_macOSFuncDownloadLocation); |
|||
} |
|||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) |
|||
{ |
|||
return Environment.ExpandEnvironmentVariables(_linuxFuncDownloadLocation); |
|||
} |
|||
else |
|||
{ |
|||
throw new NotSupportedException("OS platform not supported."); |
|||
} |
|||
} |
|||
|
|||
public string GetAzureFunctionDirectoryWithVersion(string preciseVersion) |
|||
{ |
|||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
|||
{ |
|||
// Default is min.win for whatever reason, probably minified win
|
|||
return Environment.ExpandEnvironmentVariables(Path.Combine(WindowsFuncDownloadLocation, preciseVersion)); |
|||
} |
|||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
|||
{ |
|||
return Environment.ExpandEnvironmentVariables(Path.Combine(_macOSFuncDownloadLocation, preciseVersion)); |
|||
} |
|||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) |
|||
{ |
|||
return Environment.ExpandEnvironmentVariables(Path.Combine(_linuxFuncDownloadLocation, preciseVersion)); |
|||
} |
|||
else |
|||
{ |
|||
throw new NotSupportedException("OS platform not supported."); |
|||
} |
|||
} |
|||
|
|||
public static string GetFuncName() |
|||
{ |
|||
return "func.dll"; |
|||
} |
|||
|
|||
private static string GetOsName() |
|||
{ |
|||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
|||
{ |
|||
// Default is min.win for whatever reason, probably minified win
|
|||
return "Windows"; |
|||
} |
|||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
|||
{ |
|||
return "MacOS"; |
|||
} |
|||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) |
|||
{ |
|||
return "Linux"; |
|||
} |
|||
else |
|||
{ |
|||
throw new NotSupportedException("OS platform not supported."); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,54 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System.Collections.Generic; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Tye.Hosting.Model; |
|||
|
|||
namespace Microsoft.Tye.Hosting |
|||
{ |
|||
public class FuncDownloader : IApplicationProcessor |
|||
{ |
|||
private readonly ILogger _logger; |
|||
private readonly CancellationTokenSource _cancellationTokenSource; |
|||
|
|||
public FuncDownloader(ILogger logger) |
|||
{ |
|||
_logger = logger; |
|||
_cancellationTokenSource = new CancellationTokenSource(); |
|||
} |
|||
|
|||
public async Task StartAsync(Application application) |
|||
{ |
|||
var functions = new HashSet<AzureFunctionRunInfo>(); |
|||
|
|||
foreach (var s in application.Services) |
|||
{ |
|||
if (s.Value.Description.RunInfo is AzureFunctionRunInfo function) |
|||
{ |
|||
functions.Add(function); |
|||
} |
|||
} |
|||
|
|||
// No functions
|
|||
if (functions.Count == 0) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
foreach (var func in functions) |
|||
{ |
|||
func.FuncExecutablePath ??= await FuncDetector.Instance.PathToFunc(func.Version, func.Architecture, func.DownloadPath, _logger, _cancellationTokenSource.Token); |
|||
} |
|||
} |
|||
|
|||
public Task StopAsync(Application application) |
|||
{ |
|||
_cancellationTokenSource.Cancel(); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using Microsoft.Extensions.Logging; |
|||
|
|||
namespace Microsoft.Tye.Hosting.Model |
|||
{ |
|||
public class AzureFunctionRunInfo : RunInfo |
|||
{ |
|||
public AzureFunctionRunInfo(AzureFunctionServiceBuilder function) |
|||
{ |
|||
Args = function.Args; |
|||
FunctionPath = function.FunctionPath; |
|||
Version = function.Version; |
|||
Architecture = function.Architecture; |
|||
FuncExecutablePath = function.FuncExecutablePath; |
|||
} |
|||
|
|||
public string? Args { get; } |
|||
public string FunctionPath { get; } |
|||
public string? Version { get; } |
|||
public string? Architecture { get; } |
|||
public string? FuncExecutablePath { get; set; } |
|||
public string? DownloadPath { get; } |
|||
} |
|||
} |
|||
@ -0,0 +1,264 @@ |
|||
## Ignore Visual Studio temporary files, build results, and |
|||
## files generated by popular Visual Studio add-ons. |
|||
|
|||
# Azure Functions localsettings file |
|||
local.settings.json |
|||
|
|||
# User-specific files |
|||
*.suo |
|||
*.user |
|||
*.userosscache |
|||
*.sln.docstates |
|||
|
|||
# User-specific files (MonoDevelop/Xamarin Studio) |
|||
*.userprefs |
|||
|
|||
# Build results |
|||
[Dd]ebug/ |
|||
[Dd]ebugPublic/ |
|||
[Rr]elease/ |
|||
[Rr]eleases/ |
|||
x64/ |
|||
x86/ |
|||
bld/ |
|||
[Bb]in/ |
|||
[Oo]bj/ |
|||
[Ll]og/ |
|||
|
|||
# Visual Studio 2015 cache/options directory |
|||
.vs/ |
|||
# Uncomment if you have tasks that create the project's static files in wwwroot |
|||
#wwwroot/ |
|||
|
|||
# MSTest test Results |
|||
[Tt]est[Rr]esult*/ |
|||
[Bb]uild[Ll]og.* |
|||
|
|||
# NUNIT |
|||
*.VisualState.xml |
|||
TestResult.xml |
|||
|
|||
# Build Results of an ATL Project |
|||
[Dd]ebugPS/ |
|||
[Rr]eleasePS/ |
|||
dlldata.c |
|||
|
|||
# DNX |
|||
project.lock.json |
|||
project.fragment.lock.json |
|||
artifacts/ |
|||
|
|||
*_i.c |
|||
*_p.c |
|||
*_i.h |
|||
*.ilk |
|||
*.meta |
|||
*.obj |
|||
*.pch |
|||
*.pdb |
|||
*.pgc |
|||
*.pgd |
|||
*.rsp |
|||
*.sbr |
|||
*.tlb |
|||
*.tli |
|||
*.tlh |
|||
*.tmp |
|||
*.tmp_proj |
|||
*.log |
|||
*.vspscc |
|||
*.vssscc |
|||
.builds |
|||
*.pidb |
|||
*.svclog |
|||
*.scc |
|||
|
|||
# Chutzpah Test files |
|||
_Chutzpah* |
|||
|
|||
# Visual C++ cache files |
|||
ipch/ |
|||
*.aps |
|||
*.ncb |
|||
*.opendb |
|||
*.opensdf |
|||
*.sdf |
|||
*.cachefile |
|||
*.VC.db |
|||
*.VC.VC.opendb |
|||
|
|||
# Visual Studio profiler |
|||
*.psess |
|||
*.vsp |
|||
*.vspx |
|||
*.sap |
|||
|
|||
# TFS 2012 Local Workspace |
|||
$tf/ |
|||
|
|||
# Guidance Automation Toolkit |
|||
*.gpState |
|||
|
|||
# ReSharper is a .NET coding add-in |
|||
_ReSharper*/ |
|||
*.[Rr]e[Ss]harper |
|||
*.DotSettings.user |
|||
|
|||
# JustCode is a .NET coding add-in |
|||
.JustCode |
|||
|
|||
# TeamCity is a build add-in |
|||
_TeamCity* |
|||
|
|||
# DotCover is a Code Coverage Tool |
|||
*.dotCover |
|||
|
|||
# NCrunch |
|||
_NCrunch_* |
|||
.*crunch*.local.xml |
|||
nCrunchTemp_* |
|||
|
|||
# MightyMoose |
|||
*.mm.* |
|||
AutoTest.Net/ |
|||
|
|||
# Web workbench (sass) |
|||
.sass-cache/ |
|||
|
|||
# Installshield output folder |
|||
[Ee]xpress/ |
|||
|
|||
# DocProject is a documentation generator add-in |
|||
DocProject/buildhelp/ |
|||
DocProject/Help/*.HxT |
|||
DocProject/Help/*.HxC |
|||
DocProject/Help/*.hhc |
|||
DocProject/Help/*.hhk |
|||
DocProject/Help/*.hhp |
|||
DocProject/Help/Html2 |
|||
DocProject/Help/html |
|||
|
|||
# Click-Once directory |
|||
publish/ |
|||
|
|||
# Publish Web Output |
|||
*.[Pp]ublish.xml |
|||
*.azurePubxml |
|||
# TODO: Comment the next line if you want to checkin your web deploy settings |
|||
# but database connection strings (with potential passwords) will be unencrypted |
|||
#*.pubxml |
|||
*.publishproj |
|||
|
|||
# Microsoft Azure Web App publish settings. Comment the next line if you want to |
|||
# checkin your Azure Web App publish settings, but sensitive information contained |
|||
# in these scripts will be unencrypted |
|||
PublishScripts/ |
|||
|
|||
# NuGet Packages |
|||
*.nupkg |
|||
# The packages folder can be ignored because of Package Restore |
|||
**/packages/* |
|||
# except build/, which is used as an MSBuild target. |
|||
!**/packages/build/ |
|||
# Uncomment if necessary however generally it will be regenerated when needed |
|||
#!**/packages/repositories.config |
|||
# NuGet v3's project.json files produces more ignoreable files |
|||
*.nuget.props |
|||
*.nuget.targets |
|||
|
|||
# Microsoft Azure Build Output |
|||
csx/ |
|||
*.build.csdef |
|||
|
|||
# Microsoft Azure Emulator |
|||
ecf/ |
|||
rcf/ |
|||
|
|||
# Windows Store app package directories and files |
|||
AppPackages/ |
|||
BundleArtifacts/ |
|||
Package.StoreAssociation.xml |
|||
_pkginfo.txt |
|||
|
|||
# Visual Studio cache files |
|||
# files ending in .cache can be ignored |
|||
*.[Cc]ache |
|||
# but keep track of directories ending in .cache |
|||
!*.[Cc]ache/ |
|||
|
|||
# Others |
|||
ClientBin/ |
|||
~$* |
|||
*~ |
|||
*.dbmdl |
|||
*.dbproj.schemaview |
|||
*.jfm |
|||
*.pfx |
|||
*.publishsettings |
|||
node_modules/ |
|||
orleans.codegen.cs |
|||
|
|||
# Since there are multiple workflows, uncomment next line to ignore bower_components |
|||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) |
|||
#bower_components/ |
|||
|
|||
# RIA/Silverlight projects |
|||
Generated_Code/ |
|||
|
|||
# Backup & report files from converting an old project file |
|||
# to a newer Visual Studio version. Backup files are not needed, |
|||
# because we have git ;-) |
|||
_UpgradeReport_Files/ |
|||
Backup*/ |
|||
UpgradeLog*.XML |
|||
UpgradeLog*.htm |
|||
|
|||
# SQL Server files |
|||
*.mdf |
|||
*.ldf |
|||
|
|||
# Business Intelligence projects |
|||
*.rdl.data |
|||
*.bim.layout |
|||
*.bim_*.settings |
|||
|
|||
# Microsoft Fakes |
|||
FakesAssemblies/ |
|||
|
|||
# GhostDoc plugin setting file |
|||
*.GhostDoc.xml |
|||
|
|||
# Node.js Tools for Visual Studio |
|||
.ntvs_analysis.dat |
|||
|
|||
# Visual Studio 6 build log |
|||
*.plg |
|||
|
|||
# Visual Studio 6 workspace options file |
|||
*.opt |
|||
|
|||
# Visual Studio LightSwitch build output |
|||
**/*.HTMLClient/GeneratedArtifacts |
|||
**/*.DesktopClient/GeneratedArtifacts |
|||
**/*.DesktopClient/ModelManifest.xml |
|||
**/*.Server/GeneratedArtifacts |
|||
**/*.Server/ModelManifest.xml |
|||
_Pvt_Extensions |
|||
|
|||
# Paket dependency manager |
|||
.paket/paket.exe |
|||
paket-files/ |
|||
|
|||
# FAKE - F# Make |
|||
.fake/ |
|||
|
|||
# JetBrains Rider |
|||
.idea/ |
|||
*.sln.iml |
|||
|
|||
# CodeRush |
|||
.cr/ |
|||
|
|||
# Python Tools for Visual Studio (PTVS) |
|||
__pycache__/ |
|||
*.pyc |
|||
@ -0,0 +1,38 @@ |
|||
using System; |
|||
using System.IO; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Mvc; |
|||
using Microsoft.Azure.WebJobs; |
|||
using Microsoft.Azure.WebJobs.Extensions.Http; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.Extensions.Logging; |
|||
using Newtonsoft.Json; |
|||
|
|||
namespace backend |
|||
{ |
|||
public static class backend |
|||
{ |
|||
[FunctionName("backend")] |
|||
public static async Task<IActionResult> Run( |
|||
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, |
|||
ILogger log) |
|||
{ |
|||
log.LogInformation("C# HTTP trigger function processed a request."); |
|||
|
|||
var backendInfo = new BackendInfo() |
|||
{ |
|||
IP = req.HttpContext.Connection.LocalIpAddress.ToString(), |
|||
Hostname = System.Net.Dns.GetHostName(), |
|||
}; |
|||
|
|||
return new OkObjectResult(backendInfo); |
|||
} |
|||
|
|||
class BackendInfo |
|||
{ |
|||
public string IP { get; set; } = default!; |
|||
|
|||
public string Hostname { get; set; } = default!; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,18 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
<PropertyGroup> |
|||
<TargetFramework>netcoreapp3.1</TargetFramework> |
|||
<AzureFunctionsVersion>v3</AzureFunctionsVersion> |
|||
</PropertyGroup> |
|||
<ItemGroup> |
|||
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" /> |
|||
</ItemGroup> |
|||
<ItemGroup> |
|||
<None Update="host.json"> |
|||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> |
|||
</None> |
|||
<None Update="local.settings.json"> |
|||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> |
|||
<CopyToPublishDirectory>Never</CopyToPublishDirectory> |
|||
</None> |
|||
</ItemGroup> |
|||
</Project> |
|||
@ -0,0 +1,11 @@ |
|||
{ |
|||
"version": "2.0", |
|||
"logging": { |
|||
"applicationInsights": { |
|||
"samplingExcludedTypes": "Request", |
|||
"samplingSettings": { |
|||
"isEnabled": true |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,7 @@ |
|||
{ |
|||
"IsEncrypted": false, |
|||
"Values": { |
|||
"AzureWebJobsStorage": "UseDevelopmentStorage=true", |
|||
"FUNCTIONS_WORKER_RUNTIME": "dotnet" |
|||
} |
|||
} |
|||
@ -0,0 +1,99 @@ |
|||
kind: Deployment |
|||
apiVersion: apps/v1 |
|||
metadata: |
|||
name: backend |
|||
labels: |
|||
app.kubernetes.io/name: backend |
|||
app.kubernetes.io/part-of: frontend-backend |
|||
spec: |
|||
selector: |
|||
matchLabels: |
|||
app.kubernetes.io/name: backend |
|||
template: |
|||
metadata: |
|||
labels: |
|||
app.kubernetes.io/name: backend |
|||
app.kubernetes.io/part-of: frontend-backend |
|||
spec: |
|||
containers: |
|||
- name: backend |
|||
image: rynowak/backend:0.1.17-alpha.gd8612934f5 |
|||
env: |
|||
- name: ASPNETCORE_URLS |
|||
value: http://*:5050 |
|||
- name: SERVICE__FRONTEND__PORT |
|||
value: '5051' |
|||
- name: SERVICE__FRONTEND__HOST |
|||
value: 'frontend' |
|||
ports: |
|||
- containerPort: 5050 |
|||
... |
|||
--- |
|||
kind: Service |
|||
apiVersion: v1 |
|||
metadata: |
|||
name: backend |
|||
labels: |
|||
app.kubernetes.io/name: backend |
|||
app.kubernetes.io/part-of: frontend-backend |
|||
spec: |
|||
selector: |
|||
app.kubernetes.io/name: backend |
|||
type: ClusterIP |
|||
ports: |
|||
- name: web |
|||
protocol: TCP |
|||
port: 5050 |
|||
targetPort: 5050 |
|||
... |
|||
--- |
|||
kind: Deployment |
|||
apiVersion: apps/v1 |
|||
metadata: |
|||
name: frontend |
|||
labels: |
|||
app.kubernetes.io/name: frontend |
|||
app.kubernetes.io/part-of: frontend-backend |
|||
spec: |
|||
selector: |
|||
matchLabels: |
|||
app.kubernetes.io/name: frontend |
|||
template: |
|||
metadata: |
|||
labels: |
|||
app.kubernetes.io/name: frontend |
|||
app.kubernetes.io/part-of: frontend-backend |
|||
spec: |
|||
containers: |
|||
- name: frontend |
|||
image: rynowak/frontend:0.1.17-alpha.gd8612934f5 |
|||
env: |
|||
- name: ASPNETCORE_URLS |
|||
value: http://*:5051 |
|||
- name: SERVICE__BACKEND__PORT |
|||
value: '5050' |
|||
- name: SERVICE__BACKEND__HOST |
|||
value: 'backend' |
|||
ports: |
|||
- containerPort: 5051 |
|||
... |
|||
--- |
|||
kind: Service |
|||
apiVersion: v1 |
|||
metadata: |
|||
name: frontend |
|||
labels: |
|||
app.kubernetes.io/name: frontend |
|||
app.kubernetes.io/part-of: frontend-backend |
|||
spec: |
|||
selector: |
|||
app.kubernetes.io/name: frontend |
|||
type: ClusterIP |
|||
ports: |
|||
- name: web |
|||
protocol: TCP |
|||
port: 5051 |
|||
targetPort: 5051 |
|||
... |
|||
tPort: 5051 |
|||
... |
|||
@ -0,0 +1,48 @@ |
|||
|
|||
Microsoft Visual Studio Solution File, Format Version 12.00 |
|||
# Visual Studio 15 |
|||
VisualStudioVersion = 15.0.26124.0 |
|||
MinimumVisualStudioVersion = 15.0.26124.0 |
|||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "backend", "backend\backend.csproj", "{E900C6D9-7A87-49E3-93E5-97E6402E3939}" |
|||
EndProject |
|||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "frontend", "frontend\frontend.csproj", "{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}" |
|||
EndProject |
|||
Global |
|||
GlobalSection(SolutionConfigurationPlatforms) = preSolution |
|||
Debug|Any CPU = Debug|Any CPU |
|||
Debug|x64 = Debug|x64 |
|||
Debug|x86 = Debug|x86 |
|||
Release|Any CPU = Release|Any CPU |
|||
Release|x64 = Release|x64 |
|||
Release|x86 = Release|x86 |
|||
EndGlobalSection |
|||
GlobalSection(SolutionProperties) = preSolution |
|||
HideSolutionNode = FALSE |
|||
EndGlobalSection |
|||
GlobalSection(ProjectConfigurationPlatforms) = postSolution |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Debug|Any CPU.ActiveCfg = Debug|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Debug|Any CPU.Build.0 = Debug|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Debug|x64.ActiveCfg = Debug|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Debug|x64.Build.0 = Debug|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Debug|x86.ActiveCfg = Debug|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Debug|x86.Build.0 = Debug|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Release|Any CPU.ActiveCfg = Release|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Release|Any CPU.Build.0 = Release|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Release|x64.ActiveCfg = Release|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Release|x64.Build.0 = Release|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Release|x86.ActiveCfg = Release|Any CPU |
|||
{E900C6D9-7A87-49E3-93E5-97E6402E3939}.Release|x86.Build.0 = Release|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Debug|Any CPU.Build.0 = Debug|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Debug|x64.ActiveCfg = Debug|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Debug|x64.Build.0 = Debug|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Debug|x86.ActiveCfg = Debug|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Debug|x86.Build.0 = Debug|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Release|Any CPU.ActiveCfg = Release|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Release|Any CPU.Build.0 = Release|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Release|x64.ActiveCfg = Release|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Release|x64.Build.0 = Release|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Release|x86.ActiveCfg = Release|Any CPU |
|||
{3BCACB4B-8506-4A5C-B4EE-FC76627EBE11}.Release|x86.Build.0 = Release|Any CPU |
|||
EndGlobalSection |
|||
EndGlobal |
|||
@ -0,0 +1,24 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.Extensions.Hosting; |
|||
|
|||
namespace Frontend |
|||
{ |
|||
public class Program |
|||
{ |
|||
public static void Main(string[] args) |
|||
{ |
|||
CreateHostBuilder(args).Build().Run(); |
|||
} |
|||
|
|||
public static IHostBuilder CreateHostBuilder(string[] args) => |
|||
Host.CreateDefaultBuilder(args) |
|||
.ConfigureWebHostDefaults(webBuilder => |
|||
{ |
|||
webBuilder.UseStartup<Startup>(); |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
{ |
|||
"iisSettings": { |
|||
"windowsAuthentication": false, |
|||
"anonymousAuthentication": true, |
|||
"iisExpress": { |
|||
"applicationUrl": "http://localhost:16377", |
|||
"sslPort": 44392 |
|||
} |
|||
}, |
|||
"profiles": { |
|||
"IIS Express": { |
|||
"commandName": "IISExpress", |
|||
"launchBrowser": true, |
|||
"environmentVariables": { |
|||
"ASPNETCORE_ENVIRONMENT": "Development" |
|||
} |
|||
}, |
|||
"frontend": { |
|||
"commandName": "Project", |
|||
"launchBrowser": true, |
|||
"applicationUrl": "https://localhost:5001;http://localhost:5000", |
|||
"environmentVariables": { |
|||
"ASPNETCORE_ENVIRONMENT": "Development" |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,87 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
using System.Linq; |
|||
using System.Net; |
|||
using System.Net.Http; |
|||
using System.Text.Json; |
|||
using Microsoft.AspNetCore.Builder; |
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.AspNetCore.Http.Features; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Hosting; |
|||
using Microsoft.Extensions.Logging; |
|||
|
|||
namespace Frontend |
|||
{ |
|||
public class Startup |
|||
{ |
|||
private readonly JsonSerializerOptions options = new JsonSerializerOptions() |
|||
{ |
|||
PropertyNameCaseInsensitive = true, |
|||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
|||
}; |
|||
|
|||
public Startup(IConfiguration configuration) |
|||
{ |
|||
Configuration = configuration; |
|||
} |
|||
|
|||
public IConfiguration Configuration { get; } |
|||
|
|||
public void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
services.AddHealthChecks(); |
|||
} |
|||
|
|||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) |
|||
{ |
|||
if (env.IsDevelopment()) |
|||
{ |
|||
app.UseDeveloperExceptionPage(); |
|||
} |
|||
|
|||
app.UseRouting(); |
|||
|
|||
app.UseEndpoints(endpoints => |
|||
{ |
|||
var uri = Configuration.GetServiceUri("backend")!; |
|||
|
|||
logger.LogInformation("Backend URL: {BackendUrl}", uri); |
|||
|
|||
var httpClient = new HttpClient() |
|||
{ |
|||
BaseAddress = uri |
|||
}; |
|||
|
|||
endpoints.MapGet("/", async context => |
|||
{ |
|||
var bytes = await httpClient.GetByteArrayAsync("/api/backend"); |
|||
var backendInfo = JsonSerializer.Deserialize<BackendInfo>(bytes, options); |
|||
|
|||
await context.Response.WriteAsync($"Frontend Listening IP: {context.Connection.LocalIpAddress}{Environment.NewLine}"); |
|||
await context.Response.WriteAsync($"Frontend Hostname: {Dns.GetHostName()}{Environment.NewLine}"); |
|||
await context.Response.WriteAsync($"EnvVar Configuration value: {Configuration["App:Value"]}{Environment.NewLine}"); |
|||
|
|||
await context.Response.WriteAsync($"Backend Listening IP: {backendInfo.IP}{Environment.NewLine}"); |
|||
await context.Response.WriteAsync($"Backend Hostname: {backendInfo.Hostname}{Environment.NewLine}"); |
|||
var addresses = await Dns.GetHostAddressesAsync(uri.Host); |
|||
await context.Response.WriteAsync($"Backend Host Addresses: {string.Join(", ", addresses.Select(a => a.ToString()))}"); |
|||
}); |
|||
|
|||
endpoints.MapHealthChecks("/healthz"); |
|||
}); |
|||
} |
|||
|
|||
class BackendInfo |
|||
{ |
|||
public string IP { get; set; } = default!; |
|||
|
|||
public string Hostname { get; set; } = default!; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Logging": { |
|||
"LogLevel": { |
|||
"Default": "Information", |
|||
"Microsoft": "Warning", |
|||
"Microsoft.Hosting.Lifetime": "Information" |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,10 @@ |
|||
{ |
|||
"Logging": { |
|||
"LogLevel": { |
|||
"Default": "Information", |
|||
"Microsoft": "Warning", |
|||
"Microsoft.Hosting.Lifetime": "Information" |
|||
} |
|||
}, |
|||
"AllowedHosts": "*" |
|||
} |
|||
@ -0,0 +1,12 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk.Web"> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>netcoreapp3.1</TargetFramework> |
|||
<RootNamespace>Frontend</RootNamespace> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="$(TyeLibrariesPath)\Microsoft.Tye.Extensions.Configuration\Microsoft.Tye.Extensions.Configuration.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,14 @@ |
|||
# tye application configuration file |
|||
# read all about it at https://github.com/dotnet/tye |
|||
name: frontend-backend |
|||
services: |
|||
- name: backend |
|||
project: backend/backend.csproj |
|||
buildProperties: |
|||
- name: Configuration |
|||
value: Debug |
|||
- name: frontend |
|||
project: frontend/frontend.csproj |
|||
buildProperties: |
|||
- name: Configuration |
|||
value: Debug |
|||
@ -0,0 +1,14 @@ |
|||
# tye application configuration file |
|||
# read all about it at https://github.com/dotnet/tye |
|||
name: frontend-backend |
|||
services: |
|||
- name: backend |
|||
project: backend/backend.csproj |
|||
buildProperties: |
|||
- name: Configuration |
|||
value: Release |
|||
- name: frontend |
|||
project: frontend/frontend.csproj |
|||
buildProperties: |
|||
- name: Configuration |
|||
value: Release |
|||
@ -0,0 +1,8 @@ |
|||
# tye application configuration file |
|||
# read all about it at https://github.com/dotnet/tye |
|||
name: frontend-backend |
|||
services: |
|||
- name: backend |
|||
azureFunction: backend/ |
|||
- name: frontend |
|||
project: frontend/frontend.csproj |
|||
@ -0,0 +1,308 @@ |
|||
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Diagnostics; |
|||
using System.IO; |
|||
using System.Linq; |
|||
using System.Reflection; |
|||
using System.Runtime.CompilerServices; |
|||
using System.Text; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Logging; |
|||
using Serilog; |
|||
using Serilog.Core; |
|||
using Serilog.Events; |
|||
using Serilog.Extensions.Logging; |
|||
using Xunit.Abstractions; |
|||
using ILogger = Microsoft.Extensions.Logging.ILogger; |
|||
|
|||
namespace Microsoft.AspNetCore.Testing |
|||
{ |
|||
public class AssemblyTestLog : IDisposable |
|||
{ |
|||
private static readonly string MaxPathLengthEnvironmentVariableName = "ASPNETCORE_TEST_LOG_MAXPATH"; |
|||
private static readonly string LogFileExtension = ".log"; |
|||
private static readonly int MaxPathLength = GetMaxPathLength(); |
|||
|
|||
private static readonly object _lock = new object(); |
|||
private static readonly Dictionary<Assembly, AssemblyTestLog> _logs = new Dictionary<Assembly, AssemblyTestLog>(); |
|||
|
|||
private readonly ILoggerFactory _globalLoggerFactory; |
|||
private readonly ILogger _globalLogger; |
|||
private readonly string _baseDirectory; |
|||
private readonly Assembly _assembly; |
|||
private readonly IServiceProvider _serviceProvider; |
|||
|
|||
private static int GetMaxPathLength() |
|||
{ |
|||
var maxPathString = Environment.GetEnvironmentVariable(MaxPathLengthEnvironmentVariableName); |
|||
var defaultMaxPath = 245; |
|||
return string.IsNullOrEmpty(maxPathString) ? defaultMaxPath : int.Parse(maxPathString); |
|||
} |
|||
|
|||
private AssemblyTestLog(ILoggerFactory globalLoggerFactory, ILogger globalLogger, string baseDirectory, Assembly assembly, IServiceProvider serviceProvider) |
|||
{ |
|||
_globalLoggerFactory = globalLoggerFactory; |
|||
_globalLogger = globalLogger; |
|||
_baseDirectory = baseDirectory; |
|||
_assembly = assembly; |
|||
_serviceProvider = serviceProvider; |
|||
} |
|||
|
|||
public IDisposable StartTestLog(ITestOutputHelper output, string className, out ILoggerFactory loggerFactory, [CallerMemberName] string testName = null) => |
|||
StartTestLog(output, className, out loggerFactory, LogLevel.Debug, testName); |
|||
|
|||
public IDisposable StartTestLog(ITestOutputHelper output, string className, out ILoggerFactory loggerFactory, LogLevel minLogLevel, [CallerMemberName] string testName = null) => |
|||
StartTestLog(output, className, out loggerFactory, minLogLevel, out var _, out var _, testName); |
|||
|
|||
internal IDisposable StartTestLog(ITestOutputHelper output, string className, out ILoggerFactory loggerFactory, LogLevel minLogLevel, out string resolvedTestName, out string logOutputDirectory, [CallerMemberName] string testName = null) |
|||
{ |
|||
var logStart = DateTimeOffset.UtcNow; |
|||
var serviceProvider = CreateLoggerServices(output, className, minLogLevel, out resolvedTestName, out logOutputDirectory, testName, logStart); |
|||
var factory = serviceProvider.GetRequiredService<ILoggerFactory>(); |
|||
loggerFactory = factory; |
|||
var logger = loggerFactory.CreateLogger("TestLifetime"); |
|||
|
|||
var stopwatch = Stopwatch.StartNew(); |
|||
|
|||
var scope = logger.BeginScope("Test: {testName}", testName); |
|||
|
|||
_globalLogger.LogInformation("Starting test {testName}", testName); |
|||
logger.LogInformation("Starting test {testName} at {logStart}", testName, logStart.ToString("s")); |
|||
|
|||
return new Disposable(() => |
|||
{ |
|||
stopwatch.Stop(); |
|||
_globalLogger.LogInformation("Finished test {testName} in {duration}s", testName, stopwatch.Elapsed.TotalSeconds); |
|||
logger.LogInformation("Finished test {testName} in {duration}s", testName, stopwatch.Elapsed.TotalSeconds); |
|||
scope.Dispose(); |
|||
factory.Dispose(); |
|||
(serviceProvider as IDisposable)?.Dispose(); |
|||
}); |
|||
} |
|||
|
|||
public ILoggerFactory CreateLoggerFactory(ITestOutputHelper output, string className, [CallerMemberName] string testName = null, DateTimeOffset? logStart = null) |
|||
=> CreateLoggerFactory(output, className, LogLevel.Trace, testName, logStart); |
|||
|
|||
public ILoggerFactory CreateLoggerFactory(ITestOutputHelper output, string className, LogLevel minLogLevel, [CallerMemberName] string testName = null, DateTimeOffset? logStart = null) |
|||
=> CreateLoggerServices(output, className, minLogLevel, out var _, out var _, testName, logStart).GetRequiredService<ILoggerFactory>(); |
|||
|
|||
public IServiceProvider CreateLoggerServices(ITestOutputHelper output, string className, LogLevel minLogLevel, out string normalizedTestName, [CallerMemberName] string testName = null, DateTimeOffset? logStart = null) |
|||
=> CreateLoggerServices(output, className, minLogLevel, out normalizedTestName, out var _, testName, logStart); |
|||
|
|||
public IServiceProvider CreateLoggerServices(ITestOutputHelper output, string className, LogLevel minLogLevel, out string normalizedTestName, out string logOutputDirectory, [CallerMemberName] string testName = null, DateTimeOffset? logStart = null) |
|||
{ |
|||
normalizedTestName = string.Empty; |
|||
logOutputDirectory = string.Empty; |
|||
var assemblyName = _assembly.GetName().Name; |
|||
|
|||
// Try to shorten the class name using the assembly name
|
|||
if (className.StartsWith(assemblyName + ".")) |
|||
{ |
|||
className = className.Substring(assemblyName.Length + 1); |
|||
} |
|||
|
|||
SerilogLoggerProvider serilogLoggerProvider = null; |
|||
if (!string.IsNullOrEmpty(_baseDirectory)) |
|||
{ |
|||
logOutputDirectory = Path.Combine(_baseDirectory, className); |
|||
testName = TestFileOutputContext.RemoveIllegalFileChars(testName); |
|||
|
|||
if (logOutputDirectory.Length + testName.Length + LogFileExtension.Length >= MaxPathLength) |
|||
{ |
|||
_globalLogger.LogWarning($"Test name {testName} is too long. Please shorten test name."); |
|||
|
|||
// Shorten the test name by removing the middle portion of the testname
|
|||
var testNameLength = MaxPathLength - logOutputDirectory.Length - LogFileExtension.Length; |
|||
|
|||
if (testNameLength <= 0) |
|||
{ |
|||
throw new InvalidOperationException("Output file path could not be constructed due to max path length restrictions. Please shorten test assembly, class or method names."); |
|||
} |
|||
|
|||
testName = testName.Substring(0, testNameLength / 2) + testName.Substring(testName.Length - testNameLength / 2, testNameLength / 2); |
|||
|
|||
_globalLogger.LogWarning($"To prevent long paths test name was shortened to {testName}."); |
|||
} |
|||
|
|||
var testOutputFile = Path.Combine(logOutputDirectory, $"{testName}{LogFileExtension}"); |
|||
|
|||
if (File.Exists(testOutputFile)) |
|||
{ |
|||
_globalLogger.LogWarning($"Output log file {testOutputFile} already exists. Please try to keep log file names unique."); |
|||
|
|||
for (var i = 0; i < 1000; i++) |
|||
{ |
|||
testOutputFile = Path.Combine(logOutputDirectory, $"{testName}.{i}{LogFileExtension}"); |
|||
|
|||
if (!File.Exists(testOutputFile)) |
|||
{ |
|||
_globalLogger.LogWarning($"To resolve log file collision, the enumerated file {testOutputFile} will be used."); |
|||
testName = $"{testName}.{i}"; |
|||
break; |
|||
} |
|||
} |
|||
} |
|||
|
|||
normalizedTestName = testName; |
|||
serilogLoggerProvider = ConfigureFileLogging(testOutputFile, logStart); |
|||
} |
|||
|
|||
var serviceCollection = new ServiceCollection(); |
|||
serviceCollection.AddLogging(builder => |
|||
{ |
|||
builder.SetMinimumLevel(minLogLevel); |
|||
|
|||
if (output != null) |
|||
{ |
|||
builder.AddXunit(output, minLogLevel, logStart); |
|||
} |
|||
|
|||
if (serilogLoggerProvider != null) |
|||
{ |
|||
// Use a factory so that the container will dispose it
|
|||
builder.Services.AddSingleton<ILoggerProvider>(_ => serilogLoggerProvider); |
|||
} |
|||
}); |
|||
|
|||
return serviceCollection.BuildServiceProvider(); |
|||
} |
|||
|
|||
// For back compat
|
|||
public static AssemblyTestLog Create(string assemblyName, string baseDirectory) |
|||
=> Create(Assembly.Load(new AssemblyName(assemblyName)), baseDirectory); |
|||
|
|||
public static AssemblyTestLog Create(Assembly assembly, string baseDirectory) |
|||
{ |
|||
var logStart = DateTimeOffset.UtcNow; |
|||
SerilogLoggerProvider serilogLoggerProvider = null; |
|||
if (!string.IsNullOrEmpty(baseDirectory)) |
|||
{ |
|||
baseDirectory = TestFileOutputContext.GetAssemblyBaseDirectory(assembly, baseDirectory); |
|||
var globalLogFileName = Path.Combine(baseDirectory, "global.log"); |
|||
serilogLoggerProvider = ConfigureFileLogging(globalLogFileName, logStart); |
|||
} |
|||
|
|||
var serviceCollection = new ServiceCollection(); |
|||
|
|||
serviceCollection.AddLogging(builder => |
|||
{ |
|||
// Global logging, when it's written, is expected to be outputted. So set the log level to minimum.
|
|||
builder.SetMinimumLevel(LogLevel.Trace); |
|||
|
|||
if (serilogLoggerProvider != null) |
|||
{ |
|||
// Use a factory so that the container will dispose it
|
|||
builder.Services.AddSingleton<ILoggerProvider>(_ => serilogLoggerProvider); |
|||
} |
|||
}); |
|||
|
|||
var serviceProvider = serviceCollection.BuildServiceProvider(); |
|||
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>(); |
|||
|
|||
var logger = loggerFactory.CreateLogger("GlobalTestLog"); |
|||
logger.LogInformation("Global Test Logging initialized at {logStart}. " |
|||
+ "Configure the output directory via 'LoggingTestingFileLoggingDirectory' MSBuild property " |
|||
+ "or set 'LoggingTestingDisableFileLogging' to 'true' to disable file logging.", |
|||
logStart.ToString("s")); |
|||
return new AssemblyTestLog(loggerFactory, logger, baseDirectory, assembly, serviceProvider); |
|||
} |
|||
|
|||
public static AssemblyTestLog ForAssembly(Assembly assembly) |
|||
{ |
|||
lock (_lock) |
|||
{ |
|||
if (!_logs.TryGetValue(assembly, out var log)) |
|||
{ |
|||
var baseDirectory = TestFileOutputContext.GetOutputDirectory(assembly); |
|||
|
|||
log = Create(assembly, baseDirectory); |
|||
_logs[assembly] = log; |
|||
|
|||
// Try to clear previous logs, continue if it fails.
|
|||
var assemblyBaseDirectory = TestFileOutputContext.GetAssemblyBaseDirectory(assembly); |
|||
if (!string.IsNullOrEmpty(assemblyBaseDirectory) && !TestFileOutputContext.GetPreserveExistingLogsInOutput(assembly)) |
|||
{ |
|||
try |
|||
{ |
|||
Directory.Delete(assemblyBaseDirectory, recursive: true); |
|||
} |
|||
catch { } |
|||
} |
|||
} |
|||
return log; |
|||
} |
|||
} |
|||
|
|||
private static TestFrameworkFileLoggerAttribute GetFileLoggerAttribute(Assembly assembly) |
|||
=> assembly.GetCustomAttribute<TestFrameworkFileLoggerAttribute>() |
|||
?? throw new InvalidOperationException($"No {nameof(TestFrameworkFileLoggerAttribute)} found on the assembly {assembly.GetName().Name}. " |
|||
+ "The attribute is added via msbuild properties of the Microsoft.Extensions.Logging.Testing. " |
|||
+ "Please ensure the msbuild property is imported or a direct reference to Microsoft.Extensions.Logging.Testing is added."); |
|||
|
|||
private static SerilogLoggerProvider ConfigureFileLogging(string fileName, DateTimeOffset? logStart) |
|||
{ |
|||
var dir = Path.GetDirectoryName(fileName); |
|||
if (!Directory.Exists(dir)) |
|||
{ |
|||
Directory.CreateDirectory(dir); |
|||
} |
|||
|
|||
if (File.Exists(fileName)) |
|||
{ |
|||
File.Delete(fileName); |
|||
} |
|||
|
|||
var serilogger = new LoggerConfiguration() |
|||
.Enrich.FromLogContext() |
|||
.Enrich.With(new AssemblyLogTimestampOffsetEnricher(logStart)) |
|||
.MinimumLevel.Verbose() |
|||
.WriteTo.File(fileName, outputTemplate: "[{TimestampOffset}] [{SourceContext}] [{Level}] {Message:l}{NewLine}{Exception}", flushToDiskInterval: TimeSpan.FromSeconds(1), shared: true) |
|||
.CreateLogger(); |
|||
return new SerilogLoggerProvider(serilogger, dispose: true); |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
(_serviceProvider as IDisposable)?.Dispose(); |
|||
_globalLoggerFactory.Dispose(); |
|||
} |
|||
|
|||
private class AssemblyLogTimestampOffsetEnricher : ILogEventEnricher |
|||
{ |
|||
private DateTimeOffset? _logStart; |
|||
|
|||
public AssemblyLogTimestampOffsetEnricher(DateTimeOffset? logStart) |
|||
{ |
|||
_logStart = logStart; |
|||
} |
|||
|
|||
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) |
|||
=> logEvent.AddPropertyIfAbsent( |
|||
propertyFactory.CreateProperty( |
|||
"TimestampOffset", |
|||
_logStart.HasValue |
|||
? $"{(DateTimeOffset.UtcNow - _logStart.Value).TotalSeconds.ToString("N3")}s" |
|||
: DateTimeOffset.UtcNow.ToString("s"))); |
|||
} |
|||
|
|||
private class Disposable : IDisposable |
|||
{ |
|||
private Action _action; |
|||
|
|||
public Disposable(Action action) |
|||
{ |
|||
_action = action; |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
_action(); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,26 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
using System.Reflection; |
|||
using Microsoft.AspNetCore.Testing; |
|||
using Microsoft.Extensions.Logging; |
|||
using Xunit.Abstractions; |
|||
|
|||
namespace Microsoft.AspNetCore.Testing |
|||
{ |
|||
public interface ILoggedTest : IDisposable |
|||
{ |
|||
ILogger Logger { get; } |
|||
|
|||
ILoggerFactory LoggerFactory { get; } |
|||
|
|||
ITestOutputHelper TestOutputHelper { get; } |
|||
|
|||
// For back compat
|
|||
IDisposable StartLog(out ILoggerFactory loggerFactory, LogLevel minLogLevel, string testName); |
|||
|
|||
void Initialize(TestContext context, MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper); |
|||
} |
|||
} |
|||
@ -0,0 +1,24 @@ |
|||
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
|||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
|||
|
|||
using System; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
|
|||
namespace Microsoft.AspNetCore.Testing |
|||
{ |
|||
/// <summary>
|
|||
/// Defines a lifecycle for attributes or classes that want to know about tests starting
|
|||
/// or ending. Implement this on a test class, or attribute at the method/class/assembly level.
|
|||
/// </summary>
|
|||
/// <remarks>
|
|||
/// Requires defining <see cref="AspNetTestFramework"/> as the test framework.
|
|||
/// </remarks>
|
|||
public interface ITestMethodLifecycle |
|||
{ |
|||
Task OnTestStartAsync(TestContext context, CancellationToken cancellationToken); |
|||
|
|||
Task OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken); |
|||
} |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
|
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System.Reflection; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Logging.Testing; |
|||
using Xunit.Abstractions; |
|||
|
|||
namespace Microsoft.AspNetCore.Testing |
|||
{ |
|||
public class LoggedTest : LoggedTestBase |
|||
{ |
|||
// Obsolete but keeping for back compat
|
|||
public LoggedTest(ITestOutputHelper output = null) : base(output) { } |
|||
|
|||
public ITestSink TestSink { get; set; } |
|||
|
|||
public override void Initialize(TestContext context, MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper) |
|||
{ |
|||
base.Initialize(context, methodInfo, testMethodArguments, testOutputHelper); |
|||
|
|||
TestSink = new TestSink(); |
|||
LoggerFactory.AddProvider(new TestLoggerProvider(TestSink)); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,124 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
using System.Linq; |
|||
using System.Reflection; |
|||
using System.Runtime.CompilerServices; |
|||
using System.Runtime.ExceptionServices; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Testing; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Logging.Testing; |
|||
using Serilog; |
|||
using Xunit.Abstractions; |
|||
|
|||
namespace Microsoft.AspNetCore.Testing |
|||
{ |
|||
public class LoggedTestBase : ILoggedTest, ITestMethodLifecycle |
|||
{ |
|||
private ExceptionDispatchInfo _initializationException; |
|||
|
|||
private IDisposable _testLog; |
|||
|
|||
// Obsolete but keeping for back compat
|
|||
public LoggedTestBase(ITestOutputHelper output = null) |
|||
{ |
|||
TestOutputHelper = output; |
|||
} |
|||
|
|||
protected TestContext Context { get; private set; } |
|||
|
|||
// Internal for testing
|
|||
internal string ResolvedTestClassName { get; set; } |
|||
|
|||
public string ResolvedLogOutputDirectory { get; set; } |
|||
|
|||
public string ResolvedTestMethodName { get; set; } |
|||
|
|||
public Microsoft.Extensions.Logging.ILogger Logger { get; set; } |
|||
|
|||
public ILoggerFactory LoggerFactory { get; set; } |
|||
|
|||
public ITestOutputHelper TestOutputHelper { get; set; } |
|||
|
|||
public void AddTestLogging(IServiceCollection services) => services.AddSingleton(LoggerFactory); |
|||
|
|||
// For back compat
|
|||
public IDisposable StartLog(out ILoggerFactory loggerFactory, [CallerMemberName] string testName = null) => StartLog(out loggerFactory, LogLevel.Debug, testName); |
|||
|
|||
// For back compat
|
|||
public IDisposable StartLog(out ILoggerFactory loggerFactory, LogLevel minLogLevel, [CallerMemberName] string testName = null) |
|||
{ |
|||
return AssemblyTestLog.ForAssembly(GetType().GetTypeInfo().Assembly).StartTestLog(TestOutputHelper, GetType().FullName, out loggerFactory, minLogLevel, testName); |
|||
} |
|||
|
|||
public virtual void Initialize(TestContext context, MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper) |
|||
{ |
|||
try |
|||
{ |
|||
TestOutputHelper = testOutputHelper; |
|||
|
|||
var classType = GetType(); |
|||
var logLevelAttribute = methodInfo.GetCustomAttribute<LogLevelAttribute>() |
|||
?? methodInfo.DeclaringType.GetCustomAttribute<LogLevelAttribute>() |
|||
?? methodInfo.DeclaringType.Assembly.GetCustomAttribute<LogLevelAttribute>(); |
|||
|
|||
// internal for testing
|
|||
ResolvedTestClassName = context.FileOutput.TestClassName; |
|||
|
|||
_testLog = AssemblyTestLog |
|||
.ForAssembly(classType.GetTypeInfo().Assembly) |
|||
.StartTestLog( |
|||
TestOutputHelper, |
|||
context.FileOutput.TestClassName, |
|||
out var loggerFactory, |
|||
logLevelAttribute?.LogLevel ?? LogLevel.Debug, |
|||
out var resolvedTestName, |
|||
out var logDirectory, |
|||
context.FileOutput.TestName); |
|||
|
|||
ResolvedLogOutputDirectory = logDirectory; |
|||
ResolvedTestMethodName = resolvedTestName; |
|||
|
|||
LoggerFactory = loggerFactory; |
|||
Logger = loggerFactory.CreateLogger(classType); |
|||
} |
|||
catch (Exception e) |
|||
{ |
|||
_initializationException = ExceptionDispatchInfo.Capture(e); |
|||
} |
|||
} |
|||
|
|||
public virtual void Dispose() |
|||
{ |
|||
if (_testLog == null) |
|||
{ |
|||
// It seems like sometimes the MSBuild goop that adds the test framework can end up in a bad state and not actually add it
|
|||
// Not sure yet why that happens but the exception isn't clear so I'm adding this error so we can detect it better.
|
|||
// -anurse
|
|||
throw new InvalidOperationException("LoggedTest base class was used but nothing initialized it! The test framework may not be enabled. Try cleaning your 'obj' directory."); |
|||
} |
|||
|
|||
_initializationException?.Throw(); |
|||
_testLog.Dispose(); |
|||
} |
|||
|
|||
Task ITestMethodLifecycle.OnTestStartAsync(TestContext context, CancellationToken cancellationToken) |
|||
{ |
|||
|
|||
Context = context; |
|||
|
|||
Initialize(context, context.TestMethod, context.MethodArguments, context.Output); |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
Task ITestMethodLifecycle.OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
namespace Microsoft.Extensions.Logging.Testing |
|||
{ |
|||
public class BeginScopeContext |
|||
{ |
|||
public object Scope { get; set; } |
|||
|
|||
public string LoggerName { get; set; } |
|||
} |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
using System.Collections.Concurrent; |
|||
|
|||
namespace Microsoft.Extensions.Logging.Testing |
|||
{ |
|||
public interface ITestSink |
|||
{ |
|||
event Action<WriteContext> MessageLogged; |
|||
|
|||
event Action<BeginScopeContext> ScopeStarted; |
|||
|
|||
Func<WriteContext, bool> WriteEnabled { get; set; } |
|||
|
|||
Func<BeginScopeContext, bool> BeginEnabled { get; set; } |
|||
|
|||
IProducerConsumerCollection<BeginScopeContext> Scopes { get; set; } |
|||
|
|||
IProducerConsumerCollection<WriteContext> Writes { get; set; } |
|||
|
|||
void Write(WriteContext context); |
|||
|
|||
void Begin(BeginScopeContext context); |
|||
} |
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
|
|||
namespace Microsoft.Extensions.Logging.Testing |
|||
{ |
|||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false)] |
|||
public class LogLevelAttribute : Attribute |
|||
{ |
|||
public LogLevelAttribute(LogLevel logLevel) |
|||
{ |
|||
LogLevel = logLevel; |
|||
} |
|||
|
|||
public LogLevel LogLevel { get; } |
|||
} |
|||
} |
|||
@ -0,0 +1,81 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using Xunit.Sdk; |
|||
|
|||
namespace Microsoft.Extensions.Logging.Testing |
|||
{ |
|||
public static class LogValuesAssert |
|||
{ |
|||
/// <summary>
|
|||
/// Asserts that the given key and value are present in the actual values.
|
|||
/// </summary>
|
|||
/// <param name="key">The key of the item to be found.</param>
|
|||
/// <param name="value">The value of the item to be found.</param>
|
|||
/// <param name="actualValues">The actual values.</param>
|
|||
public static void Contains( |
|||
string key, |
|||
object value, |
|||
IEnumerable<KeyValuePair<string, object>> actualValues) |
|||
{ |
|||
Contains(new[] { new KeyValuePair<string, object>(key, value) }, actualValues); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Asserts that all the expected values are present in the actual values by ignoring
|
|||
/// the order of values.
|
|||
/// </summary>
|
|||
/// <param name="expectedValues">Expected subset of values</param>
|
|||
/// <param name="actualValues">Actual set of values</param>
|
|||
public static void Contains( |
|||
IEnumerable<KeyValuePair<string, object>> expectedValues, |
|||
IEnumerable<KeyValuePair<string, object>> actualValues) |
|||
{ |
|||
if (expectedValues == null) |
|||
{ |
|||
throw new ArgumentNullException(nameof(expectedValues)); |
|||
} |
|||
|
|||
if (actualValues == null) |
|||
{ |
|||
throw new ArgumentNullException(nameof(actualValues)); |
|||
} |
|||
|
|||
var comparer = new LogValueComparer(); |
|||
|
|||
foreach (var expectedPair in expectedValues) |
|||
{ |
|||
if (!actualValues.Contains(expectedPair, comparer)) |
|||
{ |
|||
throw new EqualException( |
|||
expected: GetString(expectedValues), |
|||
actual: GetString(actualValues)); |
|||
} |
|||
} |
|||
} |
|||
|
|||
private static string GetString(IEnumerable<KeyValuePair<string, object>> logValues) |
|||
{ |
|||
return string.Join(",", logValues.Select(kvp => $"[{kvp.Key} {kvp.Value}]")); |
|||
} |
|||
|
|||
private class LogValueComparer : IEqualityComparer<KeyValuePair<string, object>> |
|||
{ |
|||
public bool Equals(KeyValuePair<string, object> x, KeyValuePair<string, object> y) |
|||
{ |
|||
return string.Equals(x.Key, y.Key) && object.Equals(x.Value, y.Value); |
|||
} |
|||
|
|||
public int GetHashCode(KeyValuePair<string, object> obj) |
|||
{ |
|||
// We are never going to put this KeyValuePair in a hash table,
|
|||
// so this is ok.
|
|||
throw new NotImplementedException(); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,77 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
using System; |
|||
|
|||
namespace Microsoft.Extensions.Logging.Testing |
|||
{ |
|||
public class TestLogger : ILogger |
|||
{ |
|||
private object _scope; |
|||
private readonly ITestSink _sink; |
|||
private readonly string _name; |
|||
private readonly Func<LogLevel, bool> _filter; |
|||
|
|||
public TestLogger(string name, ITestSink sink, bool enabled) |
|||
: this(name, sink, _ => enabled) |
|||
{ |
|||
} |
|||
|
|||
public TestLogger(string name, ITestSink sink, Func<LogLevel, bool> filter) |
|||
{ |
|||
_sink = sink; |
|||
_name = name; |
|||
_filter = filter; |
|||
} |
|||
|
|||
public string Name { get; set; } |
|||
|
|||
public IDisposable BeginScope<TState>(TState state) |
|||
{ |
|||
_scope = state; |
|||
|
|||
_sink.Begin(new BeginScopeContext() |
|||
{ |
|||
LoggerName = _name, |
|||
Scope = state, |
|||
}); |
|||
|
|||
return TestDisposable.Instance; |
|||
} |
|||
|
|||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) |
|||
{ |
|||
if (!IsEnabled(logLevel)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
_sink.Write(new WriteContext() |
|||
{ |
|||
LogLevel = logLevel, |
|||
EventId = eventId, |
|||
State = state, |
|||
Exception = exception, |
|||
Formatter = (s, e) => formatter((TState)s, e), |
|||
LoggerName = _name, |
|||
Scope = _scope |
|||
}); |
|||
} |
|||
|
|||
public bool IsEnabled(LogLevel logLevel) |
|||
{ |
|||
return logLevel != LogLevel.None && _filter(logLevel); |
|||
} |
|||
|
|||
private class TestDisposable : IDisposable |
|||
{ |
|||
public static readonly TestDisposable Instance = new TestDisposable(); |
|||
|
|||
public void Dispose() |
|||
{ |
|||
// intentionally does nothing
|
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,31 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
namespace Microsoft.Extensions.Logging.Testing |
|||
{ |
|||
public class TestLoggerFactory : ILoggerFactory |
|||
{ |
|||
private readonly ITestSink _sink; |
|||
private readonly bool _enabled; |
|||
|
|||
public TestLoggerFactory(ITestSink sink, bool enabled) |
|||
{ |
|||
_sink = sink; |
|||
_enabled = enabled; |
|||
} |
|||
|
|||
public ILogger CreateLogger(string name) |
|||
{ |
|||
return new TestLogger(name, _sink, _enabled); |
|||
} |
|||
|
|||
public void AddProvider(ILoggerProvider provider) |
|||
{ |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,25 @@ |
|||
// Licensed to the .NET Foundation under one or more agreements.
|
|||
// The .NET Foundation licenses this file to you under the MIT license.
|
|||
// See the LICENSE file in the project root for more information.
|
|||
|
|||
namespace Microsoft.Extensions.Logging.Testing |
|||
{ |
|||
public class TestLoggerProvider : ILoggerProvider |
|||
{ |
|||
private readonly ITestSink _sink; |
|||
|
|||
public TestLoggerProvider(ITestSink sink) |
|||
{ |
|||
_sink = sink; |
|||
} |
|||
|
|||
public ILogger CreateLogger(string categoryName) |
|||
{ |
|||
return new TestLogger(categoryName, _sink, enabled: true); |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
} |
|||
} |
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue