├── wwwroot ├── .nojekyll ├── favicon.png ├── css │ ├── open-iconic │ │ ├── font │ │ │ ├── fonts │ │ │ │ ├── open-iconic.eot │ │ │ │ ├── open-iconic.otf │ │ │ │ ├── open-iconic.ttf │ │ │ │ ├── open-iconic.woff │ │ │ │ └── open-iconic.svg │ │ │ └── css │ │ │ │ └── open-iconic-bootstrap.min.css │ │ ├── ICON-LICENSE │ │ ├── README.md │ │ └── FONT-LICENSE │ └── app.css ├── index.html └── fileinput.js ├── Shared └── MainLayout.razor ├── assets ├── bulb.png └── sourcegendev.gif ├── version.json ├── Samples ├── Hello World.Program.cs ├── Dependency Injection.Program.cs ├── Enum Validator.Program.cs ├── Auto Notify.Program.cs ├── Hello World.Generator.cs ├── Enum Validator.Generator.cs ├── Auto Notify.Generator.cs └── Dependency Injection.Generator.cs ├── App.razor ├── IRunner.cs ├── _Imports.razor ├── Program.cs ├── .github └── workflows │ └── publish.yml ├── Properties └── launchSettings.json ├── LICENSE.txt ├── SourceGeneratorPlayground.sln ├── SamplesLoader.cs ├── README.md ├── SourceGeneratorPlayground.csproj ├── .gitattributes ├── LRUCache.cs ├── Pages └── Index.razor ├── .gitignore ├── .editorconfig └── Runner.cs /wwwroot/.nojekyll: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Shared/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | @Body 4 | -------------------------------------------------------------------------------- /assets/bulb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwengier/SourceGeneratorPlayground/HEAD/assets/bulb.png -------------------------------------------------------------------------------- /wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwengier/SourceGeneratorPlayground/HEAD/wwwroot/favicon.png -------------------------------------------------------------------------------- /assets/sourcegendev.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwengier/SourceGeneratorPlayground/HEAD/assets/sourcegendev.gif -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/font/fonts/open-iconic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwengier/SourceGeneratorPlayground/HEAD/wwwroot/css/open-iconic/font/fonts/open-iconic.eot -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/font/fonts/open-iconic.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwengier/SourceGeneratorPlayground/HEAD/wwwroot/css/open-iconic/font/fonts/open-iconic.otf -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/font/fonts/open-iconic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwengier/SourceGeneratorPlayground/HEAD/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/font/fonts/open-iconic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwengier/SourceGeneratorPlayground/HEAD/wwwroot/css/open-iconic/font/fonts/open-iconic.woff -------------------------------------------------------------------------------- /version.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", 3 | "version": "1.0" 4 | } -------------------------------------------------------------------------------- /Samples/Hello World.Program.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace MyApp 3 | { 4 | class Program 5 | { 6 | static void Main() 7 | { 8 | HelloWorldGenerated.HelloWorld.SayHello(); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /App.razor: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |

Sorry, there's nothing at this address.

8 |
9 |
10 |
11 | -------------------------------------------------------------------------------- /IRunner.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | namespace SourceGeneratorPlayground 5 | { 6 | internal interface IRunner 7 | { 8 | string ErrorText { get; } 9 | string GeneratorOutput { get; } 10 | string ProgramOutput { get; } 11 | 12 | Task RunAsync(string code, string generator, CancellationToken cancellationToken); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.WebAssembly.Http 7 | @using Microsoft.JSInterop 8 | @using SourceGeneratorPlayground 9 | @using SourceGeneratorPlayground.Shared 10 | 11 | @using BlazorMonaco 12 | @using BlazorMonaco.Bridge -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Threading.Tasks; 4 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 5 | using Microsoft.Extensions.DependencyInjection; 6 | 7 | namespace SourceGeneratorPlayground 8 | { 9 | public class Program 10 | { 11 | public static async Task Main(string[] args) 12 | { 13 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 14 | builder.RootComponents.Add("app"); 15 | 16 | builder.Services.AddScoped(); 17 | 18 | await builder.Build().RunAsync(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: DeployToGitHubPages 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | with: 13 | fetch-depth: 0 # avoid shallow clone so nbgv can do its work. 14 | 15 | - name: Publish app 16 | run: dotnet publish -c Release 17 | 18 | - name: GitHub Pages 19 | if: success() 20 | uses: crazy-max/ghaction-github-pages@v2.2.0 21 | with: 22 | target_branch: gh-pages 23 | build_dir: bin/Release/netstandard2.1/publish/wwwroot 24 | env: 25 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | -------------------------------------------------------------------------------- /Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:65202", 7 | "sslPort": 44381 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "SourceGeneratorPlayground": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 23 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Samples/Dependency Injection.Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MyApp 4 | { 5 | class Program 6 | { 7 | static void Main() 8 | { 9 | // Comment and uncomment these lines to see how the generation changes 10 | var foo = DI.ServiceLocator.GetService(); 11 | 12 | var anotherFoo = DI.ServiceLocator.GetService(); 13 | 14 | var bar = DI.ServiceLocator.GetService(); 15 | 16 | //// Uncomment to demonstrate build errors: 17 | // var baz = DI.ServiceLocator.GetService(); 18 | 19 | Console.WriteLine("Hello World"); 20 | } 21 | } 22 | 23 | //// Comment and uncomment the attribute to see how the generation changes 24 | //[DI.Transient] 25 | interface IFoo 26 | { 27 | } 28 | 29 | class Foo : IFoo 30 | { 31 | } 32 | 33 | interface IBar 34 | { 35 | } 36 | 37 | class Bar : IBar 38 | { 39 | } 40 | 41 | interface IBaz 42 | { 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 David Wengier 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Samples/Enum Validator.Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsoleApp 4 | { 5 | public class Program 6 | { 7 | public static void Main(string[] args) 8 | { 9 | DoSomethingSimple(Simple.Second); 10 | DoSomethingComplex(Complex.Fourth); 11 | 12 | // This one is invalid! 13 | DoSomethingComplex((Complex)5); 14 | } 15 | 16 | static void DoSomethingSimple(Simple simple) 17 | { 18 | EnumValidation.EnumValidator.Validate(simple); 19 | 20 | Console.WriteLine("Doing someting complex with " + simple); 21 | } 22 | 23 | static void DoSomethingComplex(Complex complex) 24 | { 25 | EnumValidation.EnumValidator.Validate(complex); 26 | 27 | Console.WriteLine("Doing someting complex with " + complex); 28 | } 29 | } 30 | 31 | enum Simple 32 | { 33 | First, 34 | Second 35 | } 36 | 37 | enum Complex 38 | { 39 | First = 3, 40 | Second = 4, 41 | Third = 7, 42 | Fourth = 8, 43 | Fifth = 9 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/ICON-LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Waybury 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /SourceGeneratorPlayground.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30404.54 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SourceGeneratorPlayground", "SourceGeneratorPlayground.csproj", "{B5190CA8-0E49-4760-ACD2-E431BF32F9A5}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {B5190CA8-0E49-4760-ACD2-E431BF32F9A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {B5190CA8-0E49-4760-ACD2-E431BF32F9A5}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {B5190CA8-0E49-4760-ACD2-E431BF32F9A5}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {B5190CA8-0E49-4760-ACD2-E431BF32F9A5}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {605B27E9-B040-4EAA-BCFB-B41BF28CC45B} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /SamplesLoader.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | 5 | namespace SourceGeneratorPlayground 6 | { 7 | public static class SamplesLoader 8 | { 9 | public static string[] Samples = GetSamples().ToArray(); 10 | 11 | private static IEnumerable GetSamples() 12 | { 13 | yield return " - None - "; 14 | foreach (string name in typeof(SamplesLoader).Assembly.GetManifestResourceNames()) 15 | { 16 | if (name.StartsWith("SourceGeneratorPlayground.Samples") && name.EndsWith(".Generator.cs")) 17 | { 18 | yield return name.Split(".")[2]; 19 | } 20 | } 21 | } 22 | 23 | public static (string, string) LoadSample(int index) 24 | { 25 | string name = Samples[index]; 26 | using var streamReader = new StreamReader(typeof(SamplesLoader).Assembly.GetManifestResourceStream("SourceGeneratorPlayground.Samples." + name + ".Program.cs")!); 27 | using var streamReader1 = new StreamReader(typeof(SamplesLoader).Assembly.GetManifestResourceStream("SourceGeneratorPlayground.Samples." + name + ".Generator.cs")!); 28 | 29 | return (streamReader.ReadToEnd(), streamReader1.ReadToEnd()); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Samples/Auto Notify.Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using AutoNotify; 4 | 5 | namespace GeneratedDemo 6 | { 7 | // The view model we'd like to augment 8 | public partial class ExampleViewModel 9 | { 10 | [AutoNotify] 11 | private string _text = "private field text"; 12 | 13 | [AutoNotify(PropertyName = "Count")] 14 | private int _amount = 5; 15 | } 16 | 17 | public static class Program 18 | { 19 | public static void Main() 20 | { 21 | ExampleViewModel vm = new ExampleViewModel(); 22 | 23 | // we didn't explicitly create the 'Text' property, it was generated for us 24 | string text = vm.Text; 25 | Console.WriteLine($"Text = {text}"); 26 | 27 | // Properties can have differnt names generated based on the PropertyName argument of the attribute 28 | int count = vm.Count; 29 | Console.WriteLine($"Count = {count}"); 30 | 31 | // the viewmodel will automatically implement INotifyPropertyChanged 32 | vm.PropertyChanged += (o, e) => Console.WriteLine($"Property {e.PropertyName} was changed"); 33 | vm.Text = "abc"; 34 | vm.Count = 123; 35 | 36 | // Try adding fields to the ExampleViewModel class above and tagging them with the [AutoNotify] attribute 37 | // You'll see the matching generated properties visibile in IntelliSense in realtime 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Source Generator Playground - @davidwengier 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Source Generator Playground. Loading... 18 | 19 |
20 | An unhandled error has occurred. 21 | Reload 22 | 🗙 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # !["bulb by Luca Ska from the Noun Project"](assets/bulb.png) Source Generator Playground 2 | 3 | [![License: MIT](https://img.shields.io/github/license/davidwengier/SourceGeneratorPlayground?color=blue "License: MIT")](https://choosealicense.com/licenses/mit/) 4 | [![Main build status](https://github.com/davidwengier/SourceGeneratorPlayground/workflows/DeployToGitHubPages/badge.svg "Build status")](https://github.com/davidwengier/SourceGeneratorPlayground/actions?query=workflow%3ADeployToGitHubPages) 5 | [![Join the Discord](https://img.shields.io/discord/709643112636612658?label=Discord "Join the Discord")](https://discord.gg/Yt5B58b) 6 | 7 | Source Generator Playground is a simple Blazor app that lets you experiment with a C# 9 source generator. It allows you to write a simple console application, and a source generator, and observe the generated output and the program output. 8 | 9 | ### Try it live: [https://wengier.com/SourceGeneratorPlayground](https://wengier.com/SourceGeneratorPlayground) 10 | 11 | Multiple generators can be supplied, though they all need to live in the same text box, and the generator(s) can add any number of syntax trees to the compilation. All care is taken to capture meaningful errors from compilation of the generator, the program, and the running of the program. 12 | 13 | You can browse through the in built samples to try out generators, and start modifying things to see what happens. If you want to run your own, use the Load buttons. At the moment the only references available that can be leveraged is whatever is necessary for the app itself. 14 | 15 | Feel free to log issues for feedback, or PRs for new samples etc. 16 | 17 | ![](assets/sourcegendev.gif) 18 | 19 | 20 | -------------------------------------------------------------------------------- /SourceGeneratorPlayground.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 3.0 6 | preview 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | all 27 | runtime; build; native; contentfiles; analyzers 28 | 29 | 30 | 31 | 32 | 33 | 34 | all 35 | runtime; build; native; contentfiles; analyzers; buildtransitive 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Samples/Hello World.Generator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | using Microsoft.CodeAnalysis; 6 | using Microsoft.CodeAnalysis.Text; 7 | 8 | namespace SourceGeneratorSamples 9 | { 10 | [Generator] 11 | public class HelloWorldGenerator : ISourceGenerator 12 | { 13 | public void Execute(GeneratorExecutionContext context) 14 | { 15 | // begin creating the source we'll inject into the users compilation 16 | StringBuilder sourceBuilder = new StringBuilder(@" 17 | using System; 18 | namespace HelloWorldGenerated 19 | { 20 | public static class HelloWorld 21 | { 22 | public static void SayHello() 23 | { 24 | Console.WriteLine(""Hello from generated code!""); 25 | Console.WriteLine(""The following syntax trees existed in the compilation that created this program:""); 26 | "); 27 | 28 | // using the context, get a list of syntax trees in the users compilation 29 | IEnumerable syntaxTrees = context.Compilation.SyntaxTrees; 30 | 31 | // add the filepath of each tree to the class we're building 32 | foreach (SyntaxTree tree in syntaxTrees) 33 | { 34 | sourceBuilder.AppendLine($@"Console.WriteLine(@"" - {tree.FilePath}"");"); 35 | } 36 | 37 | // finish creating the source to inject 38 | sourceBuilder.Append(@" 39 | } 40 | } 41 | }"); 42 | 43 | // inject the created source into the users compilation 44 | context.AddSource("helloWorldGenerated", sourceBuilder.ToString()); 45 | } 46 | 47 | public void Initialize(GeneratorInitializationContext context) 48 | { 49 | // No initialization required 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /wwwroot/css/app.css: -------------------------------------------------------------------------------- 1 | @import url('open-iconic/font/css/open-iconic-bootstrap.min.css'); 2 | 3 | html, body { 4 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 5 | display:flex; 6 | height: 98%; 7 | width: 99%; 8 | background-color: lightgray; 9 | } 10 | 11 | a, .btn-link { 12 | color: #0366d6; 13 | } 14 | 15 | .btn-primary { 16 | color: #fff; 17 | background-color: #1b6ec2; 18 | border-color: #1861ac; 19 | } 20 | 21 | app { 22 | padding-left: 20px; 23 | padding-top: 20px; 24 | display: flex; 25 | flex: 1 1; 26 | } 27 | 28 | .valid.modified:not([type=checkbox]) { 29 | outline: 1px solid #26b050; 30 | } 31 | 32 | .invalid { 33 | outline: 1px solid red; 34 | } 35 | 36 | .validation-message { 37 | color: red; 38 | } 39 | 40 | #blazor-error-ui { 41 | background: lightyellow; 42 | bottom: 0; 43 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 44 | display: none; 45 | left: 0; 46 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 47 | position: fixed; 48 | width: 100%; 49 | z-index: 1000; 50 | } 51 | 52 | #blazor-error-ui .dismiss { 53 | cursor: pointer; 54 | position: absolute; 55 | right: 0.75rem; 56 | top: 0.5rem; 57 | } 58 | 59 | .monaco-editor-container { 60 | height: 100%; 61 | border: 1px solid gray; 62 | } 63 | 64 | .header { 65 | font-weight: normal; 66 | font-size: 16pt; 67 | } 68 | 69 | div.refresh { 70 | position: relative; 71 | width: 160px; 72 | float: right; 73 | vertical-align: bottom; 74 | } 75 | 76 | div.refresh span { 77 | vertical-align: bottom; 78 | } 79 | 80 | div.refresh div { 81 | position: absolute; 82 | top: 0; 83 | right: 0; 84 | width: 100px; 85 | cursor: pointer; 86 | line-height: 1; 87 | } 88 | 89 | .banner { 90 | /* grid-area: 1 / 1 / 2 / 3; */ 91 | background-color: white; 92 | position: absolute; 93 | top: 0; 94 | left: 0; 95 | right: 0; 96 | border-bottom: 2px solid black; 97 | 98 | text-align: center; 99 | padding-left: 10px; 100 | padding-right: 10px; 101 | font-size: 14pt; 102 | } 103 | 104 | .banner .title { 105 | float: left; 106 | font-weight: bold; 107 | } 108 | 109 | .banner .title .version { 110 | font-size: 10pt; 111 | } 112 | 113 | .banner .about { 114 | float: right; 115 | } 116 | 117 | 118 | .parent { 119 | display: grid; 120 | grid-template-columns: repeat(2, 1fr); 121 | grid-template-rows: 2em 1fr 2em 1fr; 122 | grid-column-gap: 8px; 123 | grid-row-gap: 8px; 124 | padding-top: 20px; 125 | width: 100%; 126 | height: 100%; 127 | flex-direction: row; 128 | } 129 | 130 | .code-header { grid-area: 1 / 1 / 2 / 2; } 131 | .generator-header { grid-area: 1 / 2 / 2 / 3; } 132 | .code { grid-area: 2 / 1 / 3 / 2; } 133 | .generator { grid-area: 2 / 2 / 3 / 3; } 134 | .program-output-header { grid-area: 3 / 1 / 4 / 2; } 135 | .generator-output-header { grid-area: 3 / 2 / 4 / 3; } 136 | .program-output { grid-area: 4 / 1 / 5 / 2; } 137 | .generator-output { grid-area: 4 / 2 / 5 / 3; } 138 | 139 | .fileUpload { 140 | position: relative; 141 | overflow: hidden; 142 | width: 100px; 143 | line-height: 1; 144 | float: right; 145 | } 146 | .fileUpload input { 147 | position: absolute; 148 | top: 0; 149 | right: 0; 150 | margin: 0; 151 | padding: 0; 152 | font-size: 20px; 153 | cursor: pointer; 154 | opacity: 0; 155 | filter: alpha(opacity=0); 156 | } -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/README.md: -------------------------------------------------------------------------------- 1 | [Open Iconic v1.1.1](http://useiconic.com/open) 2 | =========== 3 | 4 | ### 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) 5 | 6 | 7 | 8 | ## What's in Open Iconic? 9 | 10 | * 223 icons designed to be legible down to 8 pixels 11 | * Super-light SVG files - 61.8 for the entire set 12 | * SVG sprite—the modern replacement for icon fonts 13 | * Webfont (EOT, OTF, SVG, TTF, WOFF), PNG and WebP formats 14 | * Webfont stylesheets (including versions for Bootstrap and Foundation) in CSS, LESS, SCSS and Stylus formats 15 | * PNG and WebP raster images in 8px, 16px, 24px, 32px, 48px and 64px. 16 | 17 | 18 | ## Getting Started 19 | 20 | #### 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. 21 | 22 | ### General Usage 23 | 24 | #### Using Open Iconic's SVGs 25 | 26 | 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). 27 | 28 | ``` 29 | icon name 30 | ``` 31 | 32 | #### Using Open Iconic's SVG Sprite 33 | 34 | 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. 35 | 36 | 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* `` *tag and a unique class name for each different icon in the* `` *tag.* 37 | 38 | ``` 39 | 40 | 41 | 42 | ``` 43 | 44 | Sizing icons only needs basic CSS. All the icons are in a square format, so just set the `` tag with equal width and height dimensions. 45 | 46 | ``` 47 | .icon { 48 | width: 16px; 49 | height: 16px; 50 | } 51 | ``` 52 | 53 | Coloring icons is even easier. All you need to do is set the `fill` rule on the `` tag. 54 | 55 | ``` 56 | .icon-account-login { 57 | fill: #f00; 58 | } 59 | ``` 60 | 61 | To learn more about SVG Sprites, read [Chris Coyier's guide](http://css-tricks.com/svg-sprites-use-better-icon-fonts/). 62 | 63 | #### Using Open Iconic's Icon Font... 64 | 65 | 66 | ##### …with Bootstrap 67 | 68 | You can find our Bootstrap stylesheets in `font/css/open-iconic-bootstrap.{css, less, scss, styl}` 69 | 70 | 71 | ``` 72 | 73 | ``` 74 | 75 | 76 | ``` 77 | 78 | ``` 79 | 80 | ##### …with Foundation 81 | 82 | You can find our Foundation stylesheets in `font/css/open-iconic-foundation.{css, less, scss, styl}` 83 | 84 | ``` 85 | 86 | ``` 87 | 88 | 89 | ``` 90 | 91 | ``` 92 | 93 | ##### …on its own 94 | 95 | You can find our default stylesheets in `font/css/open-iconic.{css, less, scss, styl}` 96 | 97 | ``` 98 | 99 | ``` 100 | 101 | ``` 102 | 103 | ``` 104 | 105 | 106 | ## License 107 | 108 | ### Icons 109 | 110 | All code (including SVG markup) is under the [MIT License](http://opensource.org/licenses/MIT). 111 | 112 | ### Fonts 113 | 114 | All fonts are under the [SIL Licensed](http://scripts.sil.org/cms/scripts/page.php?item_id=OFL_web). 115 | -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/FONT-LICENSE: -------------------------------------------------------------------------------- 1 | SIL OPEN FONT LICENSE Version 1.1 2 | 3 | Copyright (c) 2014 Waybury 4 | 5 | PREAMBLE 6 | The goals of the Open Font License (OFL) are to stimulate worldwide 7 | development of collaborative font projects, to support the font creation 8 | efforts of academic and linguistic communities, and to provide a free and 9 | open framework in which fonts may be shared and improved in partnership 10 | with others. 11 | 12 | The OFL allows the licensed fonts to be used, studied, modified and 13 | redistributed freely as long as they are not sold by themselves. The 14 | fonts, including any derivative works, can be bundled, embedded, 15 | redistributed and/or sold with any software provided that any reserved 16 | names are not used by derivative works. The fonts and derivatives, 17 | however, cannot be released under any other type of license. The 18 | requirement for fonts to remain under this license does not apply 19 | to any document created using the fonts or their derivatives. 20 | 21 | DEFINITIONS 22 | "Font Software" refers to the set of files released by the Copyright 23 | Holder(s) under this license and clearly marked as such. This may 24 | include source files, build scripts and documentation. 25 | 26 | "Reserved Font Name" refers to any names specified as such after the 27 | copyright statement(s). 28 | 29 | "Original Version" refers to the collection of Font Software components as 30 | distributed by the Copyright Holder(s). 31 | 32 | "Modified Version" refers to any derivative made by adding to, deleting, 33 | or substituting -- in part or in whole -- any of the components of the 34 | Original Version, by changing formats or by porting the Font Software to a 35 | new environment. 36 | 37 | "Author" refers to any designer, engineer, programmer, technical 38 | writer or other person who contributed to the Font Software. 39 | 40 | PERMISSION & CONDITIONS 41 | Permission is hereby granted, free of charge, to any person obtaining 42 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 43 | redistribute, and sell modified and unmodified copies of the Font 44 | Software, subject to the following conditions: 45 | 46 | 1) Neither the Font Software nor any of its individual components, 47 | in Original or Modified Versions, may be sold by itself. 48 | 49 | 2) Original or Modified Versions of the Font Software may be bundled, 50 | redistributed and/or sold with any software, provided that each copy 51 | contains the above copyright notice and this license. These can be 52 | included either as stand-alone text files, human-readable headers or 53 | in the appropriate machine-readable metadata fields within text or 54 | binary files as long as those fields can be easily viewed by the user. 55 | 56 | 3) No Modified Version of the Font Software may use the Reserved Font 57 | Name(s) unless explicit written permission is granted by the corresponding 58 | Copyright Holder. This restriction only applies to the primary font name as 59 | presented to the users. 60 | 61 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 62 | Software shall not be used to promote, endorse or advertise any 63 | Modified Version, except to acknowledge the contribution(s) of the 64 | Copyright Holder(s) and the Author(s) or with their explicit written 65 | permission. 66 | 67 | 5) The Font Software, modified or unmodified, in part or in whole, 68 | must be distributed entirely under this license, and must not be 69 | distributed under any other license. The requirement for fonts to 70 | remain under this license does not apply to any document created 71 | using the Font Software. 72 | 73 | TERMINATION 74 | This license becomes null and void if any of the above conditions are 75 | not met. 76 | 77 | DISCLAIMER 78 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 79 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 80 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 81 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 82 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 83 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 84 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 85 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 86 | OTHER DEALINGS IN THE FONT SOFTWARE. 87 | -------------------------------------------------------------------------------- /LRUCache.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * This code is based on 3 | * https://github.com/migueldeicaza/MonoTouch.Dialog/blob/e69b806efee4ead3c39926d5164c15ae90a92b7a/MonoTouch.Dialog/Utilities/LRUCache.cs 4 | * 5 | * Minor adaptations were made for compatibility with structs and classes which don't implement IDisposable 6 | */ 7 | // 8 | // A simple LRU cache used for tracking the images 9 | // 10 | // Authors: 11 | // Miguel de Icaza (miguel@gnome.org) 12 | // 13 | // Copyright 2010 Miguel de Icaza 14 | // 15 | // Permission is hereby granted, free of charge, to any person obtaining a copy 16 | // of this software and associated documentation files (the "Software"), to deal 17 | // in the Software without restriction, including without limitation the rights 18 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 19 | // copies of the Software, and to permit persons to whom the Software is 20 | // furnished to do so, subject to the following conditions: 21 | // 22 | // The above copyright notice and this permission notice shall be included in 23 | // all copies or substantial portions of the Software. 24 | // 25 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 28 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 30 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 31 | // THE SOFTWARE. 32 | // 33 | using System; 34 | using System.Collections.Generic; 35 | 36 | namespace MonoTouch.Dialog.Utilities 37 | { 38 | 39 | public class LRUCache 40 | { 41 | Dictionary> dict; 42 | Dictionary, TKey> revdict; 43 | LinkedList list; 44 | int entryLimit, sizeLimit, currentSize; 45 | Func slotSizeFunc; 46 | 47 | public LRUCache(int entryLimit) : this(entryLimit, 0, null) 48 | { 49 | } 50 | 51 | public LRUCache(int entryLimit, int sizeLimit, Func slotSizer) 52 | { 53 | list = new LinkedList(); 54 | dict = new Dictionary>(); 55 | revdict = new Dictionary, TKey>(); 56 | 57 | if (sizeLimit != 0 && slotSizer == null) 58 | throw new ArgumentNullException("If sizeLimit is set, the slotSizer must be provided"); 59 | 60 | this.entryLimit = entryLimit; 61 | this.sizeLimit = sizeLimit; 62 | slotSizeFunc = slotSizer; 63 | } 64 | 65 | void Evict() 66 | { 67 | var last = list.Last; 68 | var key = revdict[last]; 69 | 70 | if (sizeLimit > 0) 71 | { 72 | int size = slotSizeFunc(last.Value); 73 | currentSize -= size; 74 | } 75 | 76 | dict.Remove(key); 77 | revdict.Remove(last); 78 | list.RemoveLast(); 79 | (last.Value as IDisposable)?.Dispose(); 80 | } 81 | 82 | public void Purge() 83 | { 84 | foreach (var element in list) 85 | (element as IDisposable)?.Dispose(); 86 | 87 | dict.Clear(); 88 | revdict.Clear(); 89 | list.Clear(); 90 | currentSize = 0; 91 | } 92 | 93 | public TValue this[TKey key] 94 | { 95 | get 96 | { 97 | 98 | if (dict.TryGetValue(key, out LinkedListNode node)) 99 | { 100 | list.Remove(node); 101 | list.AddFirst(node); 102 | 103 | return node.Value; 104 | } 105 | return default; 106 | } 107 | 108 | set 109 | { 110 | int size = sizeLimit > 0 ? slotSizeFunc(value) : 0; 111 | 112 | if (dict.TryGetValue(key, out LinkedListNode node)) 113 | { 114 | if (sizeLimit > 0 && node.Value != null) 115 | { 116 | int repSize = slotSizeFunc(node.Value); 117 | currentSize -= repSize; 118 | currentSize += size; 119 | } 120 | 121 | // If we already have a key, move it to the front 122 | list.Remove(node); 123 | list.AddFirst(node); 124 | 125 | // Remove the old value 126 | if (node.Value != null) 127 | (node.Value as IDisposable)?.Dispose(); 128 | node.Value = value; 129 | while (sizeLimit > 0 && currentSize > sizeLimit && list.Count > 1) 130 | Evict(); 131 | return; 132 | } 133 | if (sizeLimit > 0) 134 | { 135 | while (sizeLimit > 0 && currentSize + size > sizeLimit && list.Count > 0) 136 | Evict(); 137 | } 138 | if (dict.Count >= entryLimit) 139 | Evict(); 140 | // Adding new node 141 | node = new LinkedListNode(value); 142 | list.AddFirst(node); 143 | dict[key] = node; 144 | revdict[node] = key; 145 | currentSize += size; 146 | } 147 | } 148 | 149 | public override string ToString() 150 | { 151 | return "LRUCache dict={0} revdict={1} list={2}"; 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /Pages/Index.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | @inject IRunner Runner 3 | @using BlazorInputFile 4 | @using System.Threading 5 | 6 | 22 | 23 |
24 |
Program Code
Load
25 |
26 |
Source Generator
Load
27 |
28 |
Output
29 |
30 |
Generated Output 31 |
32 | 33 | Auto 34 | 35 |
36 | Refresh 37 |
38 |
39 |
40 |
41 |
42 | 43 | @code { 44 | private MonacoEditor codeEditor; 45 | private MonacoEditor generator; 46 | private MonacoEditor programOutput; 47 | private MonacoEditor generatorOutput; 48 | private int _currentSample = 4; 49 | private bool _autoRefresh = true; 50 | 51 | protected async Task LoadSample(ChangeEventArgs e) 52 | { 53 | _currentSample = Convert.ToInt32(e.Value); 54 | if (_currentSample == 0) 55 | { 56 | await codeEditor.SetValue(""); 57 | await generator.SetValue(""); 58 | } 59 | else 60 | { 61 | var (code, gen) = SamplesLoader.LoadSample(_currentSample); 62 | 63 | await codeEditor.SetValue(code); 64 | await generator.SetValue(gen); 65 | } 66 | 67 | _ = Update(default); 68 | } 69 | 70 | private StandaloneEditorConstructionOptions EditorConstructionOptions(MonacoEditor editor) 71 | { 72 | var options = new StandaloneEditorConstructionOptions 73 | { 74 | AutomaticLayout = true, 75 | Language = "csharp", 76 | Minimap = new MinimapOptions() { Enabled = false }, 77 | Folding = false, 78 | }; 79 | 80 | if (editor == programOutput || editor == generatorOutput) 81 | { 82 | options.ReadOnly = true; 83 | } 84 | if (editor == programOutput) 85 | { 86 | options.Language = "txt"; 87 | options.LineNumbers = ""; 88 | } 89 | 90 | var (code, gen) = SamplesLoader.LoadSample(_currentSample); 91 | 92 | if (editor == codeEditor) 93 | { 94 | options.Value = code; 95 | } 96 | else if (editor == generator) 97 | { 98 | options.Value = gen; 99 | 100 | _ = Update(default); 101 | } 102 | 103 | 104 | return options; 105 | } 106 | 107 | private CancellationTokenSource _typingCancellationSource = new CancellationTokenSource(); 108 | 109 | private void Refresh() 110 | { 111 | _ = Update(default); 112 | } 113 | 114 | private void OnKeyUp(KeyboardEvent keyboardEvent) 115 | { 116 | // ignore arrow keys 117 | if (keyboardEvent.KeyCode == KeyCode.LeftArrow || 118 | keyboardEvent.KeyCode == KeyCode.RightArrow || 119 | keyboardEvent.KeyCode == KeyCode.UpArrow || 120 | keyboardEvent.KeyCode == KeyCode.DownArrow || 121 | keyboardEvent.KeyCode == KeyCode.PageUp || 122 | keyboardEvent.KeyCode == KeyCode.PageDown) 123 | { 124 | return; 125 | } 126 | 127 | if (!_autoRefresh) 128 | { 129 | return; 130 | } 131 | 132 | _typingCancellationSource.Cancel(); 133 | _typingCancellationSource = new CancellationTokenSource(); 134 | _ = Update(_typingCancellationSource.Token); 135 | } 136 | 137 | private async Task Update(CancellationToken cancellationToken) 138 | { 139 | await Task.Delay(500, cancellationToken); 140 | 141 | if (cancellationToken.IsCancellationRequested) 142 | { 143 | return; 144 | } 145 | 146 | await Runner.RunAsync(await codeEditor.GetValue(), await generator.GetValue(), cancellationToken); 147 | 148 | if (Runner.ErrorText?.Length != 0) 149 | { 150 | await programOutput.SetValue(Runner.ErrorText); 151 | } 152 | else 153 | { 154 | await programOutput.SetValue(Runner.ProgramOutput); 155 | } 156 | await generatorOutput.SetValue(Runner.GeneratorOutput); 157 | } 158 | 159 | private async Task HandleCodeFileSelected(IFileListEntry[] files) 160 | { 161 | await LoadFile(files[0], codeEditor); 162 | } 163 | 164 | private async Task HandleGeneratorFileSelected(IFileListEntry[] files) 165 | { 166 | await LoadFile(files[0], generator); 167 | } 168 | 169 | private async Task LoadFile(IFileListEntry file, MonacoEditor editor) 170 | { 171 | using (var reader = new System.IO.StreamReader(file.Data)) 172 | { 173 | await editor.SetValue(await reader.ReadToEndAsync()); 174 | } 175 | _currentSample = 0; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /Samples/Enum Validator.Generator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Text; 4 | using Microsoft.CodeAnalysis; 5 | using Microsoft.CodeAnalysis.CSharp; 6 | using Microsoft.CodeAnalysis.CSharp.Syntax; 7 | using Microsoft.CodeAnalysis.Text; 8 | 9 | namespace SourceGenerator 10 | { 11 | [Generator] 12 | public class Generator : ISourceGenerator 13 | { 14 | private const string EnumValidatorStub = @" 15 | namespace EnumValidation 16 | { 17 | internal static class EnumValidator 18 | { 19 | public static void Validate(System.Enum enumToValidate) 20 | { 21 | // This will be filled in by the generator once you call EnumValidator.Validate() 22 | // Trust me. 23 | } 24 | } 25 | } 26 | "; 27 | 28 | public void Initialize(GeneratorInitializationContext context) 29 | { 30 | // I should probably put something here 31 | } 32 | 33 | public void Execute(GeneratorExecutionContext context) 34 | { 35 | var compilation = GenerateHelperClasses(context); 36 | 37 | var enumValidatorType = compilation.GetTypeByMetadataName("EnumValidation.EnumValidator")!; 38 | 39 | var infos = GetEnumValidationInfo(compilation, enumValidatorType); 40 | 41 | if (infos.Any()) 42 | { 43 | var sb = new StringBuilder(); 44 | sb.AppendLine(@"namespace EnumValidation 45 | { 46 | internal static class EnumValidator 47 | {"); 48 | 49 | foreach (var info in infos) 50 | { 51 | sb.AppendLine(" public static void Validate(" + info.EnumType.ToString() + " enumToValidate)"); 52 | sb.AppendLine(" {"); 53 | 54 | GenerateValidator(sb, info, " "); 55 | 56 | sb.AppendLine(" }"); 57 | sb.AppendLine(); 58 | } 59 | 60 | sb.AppendLine(@" } 61 | }"); 62 | 63 | context.AddSource("Validation.cs", sb.ToString()); 64 | } 65 | else 66 | { 67 | context.AddSource("Validator.cs", EnumValidatorStub); 68 | } 69 | } 70 | 71 | private void GenerateValidator(StringBuilder sb, EnumValidationInfo info, string indent) 72 | { 73 | sb.AppendLine($"{indent}int intValue = (int)enumToValidate;"); 74 | foreach ((int min, int max) in GetElementSets(info.Elements)) 75 | { 76 | sb.AppendLine($"{indent}if (intValue >= {min} && intValue <= {max}) return;"); 77 | } 78 | sb.AppendLine($"{indent}throw new System.ComponentModel.InvalidEnumArgumentException(\"{info.ArgumentName}\", intValue, typeof({info.EnumType}));"); 79 | } 80 | 81 | private IEnumerable<(int min, int max)> GetElementSets(List<(string Name, int Value)> elements) 82 | { 83 | int min = 0; 84 | int? max = null; 85 | foreach (var info in elements) 86 | { 87 | if (max == null || info.Value != max + 1) 88 | { 89 | if (max != null) 90 | { 91 | yield return (min, max.Value); 92 | } 93 | min = info.Value; 94 | max = info.Value; 95 | } 96 | else 97 | { 98 | max = info.Value; 99 | } 100 | } 101 | yield return (min, max.Value); 102 | } 103 | 104 | private static IEnumerable GetEnumValidationInfo(Compilation compilation, INamedTypeSymbol enumValidatorType) 105 | { 106 | foreach (SyntaxTree? tree in compilation.SyntaxTrees) 107 | { 108 | var semanticModel = compilation.GetSemanticModel(tree); 109 | foreach (var invocation in tree.GetRoot().DescendantNodesAndSelf().OfType()) 110 | { 111 | var symbol = semanticModel.GetSymbolInfo(invocation).Symbol as IMethodSymbol; 112 | if (symbol == null) 113 | { 114 | continue; 115 | } 116 | 117 | if (SymbolEqualityComparer.Default.Equals(symbol.ContainingType, enumValidatorType)) 118 | { 119 | // Note: This assumes the only method on enumValidatorType is the one we want. 120 | // ie, I'm too lazy to check which invocation is being made :) 121 | var argument = invocation.ArgumentList.Arguments.First().Expression; 122 | var enumType = semanticModel.GetTypeInfo(argument).Type; 123 | if (enumType == null) 124 | { 125 | continue; 126 | } 127 | 128 | var info = new EnumValidationInfo(enumType, argument.ToString()); 129 | foreach (var member in enumType.GetMembers()) 130 | { 131 | if (member is IFieldSymbol 132 | { 133 | IsStatic: true, 134 | IsConst: true, 135 | ConstantValue: int value 136 | } field) 137 | { 138 | info.Elements.Add((field.Name, value)); 139 | } 140 | } 141 | 142 | info.Elements.Sort((e1, e2) => e1.Value.CompareTo(e2.Value)); 143 | 144 | yield return info; 145 | } 146 | } 147 | } 148 | } 149 | 150 | private static Compilation GenerateHelperClasses(GeneratorExecutionContext context) 151 | { 152 | var compilation = context.Compilation; 153 | 154 | var options = (compilation as CSharpCompilation)?.SyntaxTrees[0].Options as CSharpParseOptions; 155 | var tempCompilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(EnumValidatorStub, Encoding.UTF8), options)); 156 | 157 | return tempCompilation; 158 | } 159 | 160 | private class EnumValidationInfo 161 | { 162 | public List<(string Name, int Value)> Elements = new(); 163 | 164 | public ITypeSymbol EnumType { get; } 165 | public string ArgumentName { get; internal set; } 166 | 167 | public EnumValidationInfo(ITypeSymbol enumType, string argumentName) 168 | { 169 | this.EnumType = enumType; 170 | this.ArgumentName = argumentName; 171 | } 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | 342 | 343 | -------------------------------------------------------------------------------- /Samples/Auto Notify.Generator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | using Microsoft.CodeAnalysis; 7 | using Microsoft.CodeAnalysis.CSharp; 8 | using Microsoft.CodeAnalysis.CSharp.Syntax; 9 | using Microsoft.CodeAnalysis.Text; 10 | 11 | namespace SourceGeneratorSamples 12 | { 13 | [Generator] 14 | public class AutoNotifyGenerator : ISourceGenerator 15 | { 16 | private const string attributeText = @" 17 | using System; 18 | namespace AutoNotify 19 | { 20 | [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)] 21 | sealed class AutoNotifyAttribute : Attribute 22 | { 23 | public AutoNotifyAttribute() 24 | { 25 | } 26 | public string PropertyName { get; set; } 27 | } 28 | } 29 | "; 30 | 31 | public void Initialize(GeneratorInitializationContext context) 32 | { 33 | // Register a syntax receiver that will be created for each generation pass 34 | context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); 35 | } 36 | 37 | public void Execute(GeneratorExecutionContext context) 38 | { 39 | // add the attribute text 40 | context.AddSource("AutoNotifyAttribute", attributeText); 41 | 42 | // retreive the populated receiver 43 | if (!(context.SyntaxReceiver is SyntaxReceiver receiver)) 44 | return; 45 | 46 | // we're going to create a new compilation that contains the attribute. 47 | // TODO: we should allow source generators to provide source during initialize, so that this step isn't required. 48 | CSharpParseOptions options = (context.Compilation as CSharpCompilation).SyntaxTrees[0].Options as CSharpParseOptions; 49 | Compilation compilation = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(attributeText, Encoding.UTF8), options)); 50 | 51 | // get the newly bound attribute, and INotifyPropertyChanged 52 | INamedTypeSymbol attributeSymbol = compilation.GetTypeByMetadataName("AutoNotify.AutoNotifyAttribute"); 53 | INamedTypeSymbol notifySymbol = compilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged"); 54 | 55 | // loop over the candidate fields, and keep the ones that are actually annotated 56 | List fieldSymbols = new List(); 57 | foreach (FieldDeclarationSyntax field in receiver.CandidateFields) 58 | { 59 | SemanticModel model = compilation.GetSemanticModel(field.SyntaxTree); 60 | foreach (VariableDeclaratorSyntax variable in field.Declaration.Variables) 61 | { 62 | // Get the symbol being decleared by the field, and keep it if its annotated 63 | IFieldSymbol fieldSymbol = model.GetDeclaredSymbol(variable) as IFieldSymbol; 64 | if (fieldSymbol.GetAttributes().Any(ad => ad.AttributeClass.Equals(attributeSymbol, SymbolEqualityComparer.Default))) 65 | { 66 | fieldSymbols.Add(fieldSymbol); 67 | } 68 | } 69 | } 70 | 71 | // group the fields by class, and generate the source 72 | foreach (IGrouping group in fieldSymbols.GroupBy(f => f.ContainingType)) 73 | { 74 | string classSource = ProcessClass(group.Key, group.ToList(), attributeSymbol, notifySymbol, context); 75 | context.AddSource($"{group.Key.Name}_autoNotify.cs", classSource); 76 | } 77 | } 78 | 79 | private string ProcessClass(INamedTypeSymbol classSymbol, List fields, ISymbol attributeSymbol, ISymbol notifySymbol, GeneratorExecutionContext context) 80 | { 81 | if (!classSymbol.ContainingSymbol.Equals(classSymbol.ContainingNamespace, SymbolEqualityComparer.Default)) 82 | { 83 | return null; //TODO: issue a diagnostic that it must be top level 84 | } 85 | 86 | string namespaceName = classSymbol.ContainingNamespace.ToDisplayString(); 87 | 88 | // begin building the generated source 89 | StringBuilder source = new StringBuilder($@" 90 | namespace {namespaceName} 91 | {{ 92 | public partial class {classSymbol.Name} : {notifySymbol.ToDisplayString()} 93 | {{ 94 | "); 95 | 96 | // if the class doesn't implement INotifyPropertyChanged already, add it 97 | if (!classSymbol.Interfaces.Contains(notifySymbol)) 98 | { 99 | source.Append("public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;"); 100 | } 101 | 102 | // create properties for each field 103 | foreach (IFieldSymbol fieldSymbol in fields) 104 | { 105 | ProcessField(source, fieldSymbol, attributeSymbol); 106 | } 107 | 108 | source.Append("} }"); 109 | return source.ToString(); 110 | } 111 | 112 | private void ProcessField(StringBuilder source, IFieldSymbol fieldSymbol, ISymbol attributeSymbol) 113 | { 114 | // get the name and type of the field 115 | string fieldName = fieldSymbol.Name; 116 | ITypeSymbol fieldType = fieldSymbol.Type; 117 | 118 | // get the AutoNotify attribute from the field, and any associated data 119 | AttributeData attributeData = fieldSymbol.GetAttributes().Single(ad => ad.AttributeClass.Equals(attributeSymbol, SymbolEqualityComparer.Default)); 120 | TypedConstant overridenNameOpt = attributeData.NamedArguments.SingleOrDefault(kvp => kvp.Key == "PropertyName").Value; 121 | 122 | string propertyName = chooseName(fieldName, overridenNameOpt); 123 | if (propertyName.Length == 0 || propertyName == fieldName) 124 | { 125 | //TODO: issue a diagnostic that we can't process this field 126 | return; 127 | } 128 | 129 | source.Append($@" 130 | public {fieldType} {propertyName} 131 | {{ 132 | get 133 | {{ 134 | return this.{fieldName}; 135 | }} 136 | 137 | set 138 | {{ 139 | this.{fieldName} = value; 140 | this.PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(nameof({propertyName}))); 141 | }} 142 | }} 143 | 144 | "); 145 | 146 | string chooseName(string fieldName, TypedConstant overridenNameOpt) 147 | { 148 | if (!overridenNameOpt.IsNull) 149 | { 150 | return overridenNameOpt.Value.ToString(); 151 | } 152 | 153 | fieldName = fieldName.TrimStart('_'); 154 | if (fieldName.Length == 0) 155 | return string.Empty; 156 | 157 | if (fieldName.Length == 1) 158 | return fieldName.ToUpper(); 159 | 160 | return fieldName.Substring(0, 1).ToUpper() + fieldName.Substring(1); 161 | } 162 | 163 | } 164 | 165 | /// 166 | /// Created on demand before each generation pass 167 | /// 168 | class SyntaxReceiver : ISyntaxReceiver 169 | { 170 | public List CandidateFields { get; } = new List(); 171 | 172 | /// 173 | /// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation 174 | /// 175 | public void OnVisitSyntaxNode(SyntaxNode syntaxNode) 176 | { 177 | // any field with at least one attribute is a candidate for property generation 178 | if (syntaxNode is FieldDeclarationSyntax fieldDeclarationSyntax 179 | && fieldDeclarationSyntax.AttributeLists.Count > 0) 180 | { 181 | CandidateFields.Add(fieldDeclarationSyntax); 182 | } 183 | } 184 | } 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/font/css/open-iconic-bootstrap.min.css: -------------------------------------------------------------------------------- 1 | @font-face{font-family:Icons;src:url(../fonts/open-iconic.eot);src:url(../fonts/open-iconic.eot?#iconic-sm) format('embedded-opentype'),url(../fonts/open-iconic.woff) format('woff'),url(../fonts/open-iconic.ttf) format('truetype'),url(../fonts/open-iconic.otf) format('opentype'),url(../fonts/open-iconic.svg#iconic-sm) format('svg');font-weight:400;font-style:normal}.oi{position:relative;top:1px;display:inline-block;speak:none;font-family:Icons;font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.oi:empty:before{width:1em;text-align:center;box-sizing:content-box}.oi.oi-align-center:before{text-align:center}.oi.oi-align-left:before{text-align:left}.oi.oi-align-right:before{text-align:right}.oi.oi-flip-horizontal:before{-webkit-transform:scale(-1,1);-ms-transform:scale(-1,1);transform:scale(-1,1)}.oi.oi-flip-vertical:before{-webkit-transform:scale(1,-1);-ms-transform:scale(-1,1);transform:scale(1,-1)}.oi.oi-flip-horizontal-vertical:before{-webkit-transform:scale(-1,-1);-ms-transform:scale(-1,1);transform:scale(-1,-1)}.oi-account-login:before{content:'\e000'}.oi-account-logout:before{content:'\e001'}.oi-action-redo:before{content:'\e002'}.oi-action-undo:before{content:'\e003'}.oi-align-center:before{content:'\e004'}.oi-align-left:before{content:'\e005'}.oi-align-right:before{content:'\e006'}.oi-aperture:before{content:'\e007'}.oi-arrow-bottom:before{content:'\e008'}.oi-arrow-circle-bottom:before{content:'\e009'}.oi-arrow-circle-left:before{content:'\e00a'}.oi-arrow-circle-right:before{content:'\e00b'}.oi-arrow-circle-top:before{content:'\e00c'}.oi-arrow-left:before{content:'\e00d'}.oi-arrow-right:before{content:'\e00e'}.oi-arrow-thick-bottom:before{content:'\e00f'}.oi-arrow-thick-left:before{content:'\e010'}.oi-arrow-thick-right:before{content:'\e011'}.oi-arrow-thick-top:before{content:'\e012'}.oi-arrow-top:before{content:'\e013'}.oi-audio-spectrum:before{content:'\e014'}.oi-audio:before{content:'\e015'}.oi-badge:before{content:'\e016'}.oi-ban:before{content:'\e017'}.oi-bar-chart:before{content:'\e018'}.oi-basket:before{content:'\e019'}.oi-battery-empty:before{content:'\e01a'}.oi-battery-full:before{content:'\e01b'}.oi-beaker:before{content:'\e01c'}.oi-bell:before{content:'\e01d'}.oi-bluetooth:before{content:'\e01e'}.oi-bold:before{content:'\e01f'}.oi-bolt:before{content:'\e020'}.oi-book:before{content:'\e021'}.oi-bookmark:before{content:'\e022'}.oi-box:before{content:'\e023'}.oi-briefcase:before{content:'\e024'}.oi-british-pound:before{content:'\e025'}.oi-browser:before{content:'\e026'}.oi-brush:before{content:'\e027'}.oi-bug:before{content:'\e028'}.oi-bullhorn:before{content:'\e029'}.oi-calculator:before{content:'\e02a'}.oi-calendar:before{content:'\e02b'}.oi-camera-slr:before{content:'\e02c'}.oi-caret-bottom:before{content:'\e02d'}.oi-caret-left:before{content:'\e02e'}.oi-caret-right:before{content:'\e02f'}.oi-caret-top:before{content:'\e030'}.oi-cart:before{content:'\e031'}.oi-chat:before{content:'\e032'}.oi-check:before{content:'\e033'}.oi-chevron-bottom:before{content:'\e034'}.oi-chevron-left:before{content:'\e035'}.oi-chevron-right:before{content:'\e036'}.oi-chevron-top:before{content:'\e037'}.oi-circle-check:before{content:'\e038'}.oi-circle-x:before{content:'\e039'}.oi-clipboard:before{content:'\e03a'}.oi-clock:before{content:'\e03b'}.oi-cloud-download:before{content:'\e03c'}.oi-cloud-upload:before{content:'\e03d'}.oi-cloud:before{content:'\e03e'}.oi-cloudy:before{content:'\e03f'}.oi-code:before{content:'\e040'}.oi-cog:before{content:'\e041'}.oi-collapse-down:before{content:'\e042'}.oi-collapse-left:before{content:'\e043'}.oi-collapse-right:before{content:'\e044'}.oi-collapse-up:before{content:'\e045'}.oi-command:before{content:'\e046'}.oi-comment-square:before{content:'\e047'}.oi-compass:before{content:'\e048'}.oi-contrast:before{content:'\e049'}.oi-copywriting:before{content:'\e04a'}.oi-credit-card:before{content:'\e04b'}.oi-crop:before{content:'\e04c'}.oi-dashboard:before{content:'\e04d'}.oi-data-transfer-download:before{content:'\e04e'}.oi-data-transfer-upload:before{content:'\e04f'}.oi-delete:before{content:'\e050'}.oi-dial:before{content:'\e051'}.oi-document:before{content:'\e052'}.oi-dollar:before{content:'\e053'}.oi-double-quote-sans-left:before{content:'\e054'}.oi-double-quote-sans-right:before{content:'\e055'}.oi-double-quote-serif-left:before{content:'\e056'}.oi-double-quote-serif-right:before{content:'\e057'}.oi-droplet:before{content:'\e058'}.oi-eject:before{content:'\e059'}.oi-elevator:before{content:'\e05a'}.oi-ellipses:before{content:'\e05b'}.oi-envelope-closed:before{content:'\e05c'}.oi-envelope-open:before{content:'\e05d'}.oi-euro:before{content:'\e05e'}.oi-excerpt:before{content:'\e05f'}.oi-expand-down:before{content:'\e060'}.oi-expand-left:before{content:'\e061'}.oi-expand-right:before{content:'\e062'}.oi-expand-up:before{content:'\e063'}.oi-external-link:before{content:'\e064'}.oi-eye:before{content:'\e065'}.oi-eyedropper:before{content:'\e066'}.oi-file:before{content:'\e067'}.oi-fire:before{content:'\e068'}.oi-flag:before{content:'\e069'}.oi-flash:before{content:'\e06a'}.oi-folder:before{content:'\e06b'}.oi-fork:before{content:'\e06c'}.oi-fullscreen-enter:before{content:'\e06d'}.oi-fullscreen-exit:before{content:'\e06e'}.oi-globe:before{content:'\e06f'}.oi-graph:before{content:'\e070'}.oi-grid-four-up:before{content:'\e071'}.oi-grid-three-up:before{content:'\e072'}.oi-grid-two-up:before{content:'\e073'}.oi-hard-drive:before{content:'\e074'}.oi-header:before{content:'\e075'}.oi-headphones:before{content:'\e076'}.oi-heart:before{content:'\e077'}.oi-home:before{content:'\e078'}.oi-image:before{content:'\e079'}.oi-inbox:before{content:'\e07a'}.oi-infinity:before{content:'\e07b'}.oi-info:before{content:'\e07c'}.oi-italic:before{content:'\e07d'}.oi-justify-center:before{content:'\e07e'}.oi-justify-left:before{content:'\e07f'}.oi-justify-right:before{content:'\e080'}.oi-key:before{content:'\e081'}.oi-laptop:before{content:'\e082'}.oi-layers:before{content:'\e083'}.oi-lightbulb:before{content:'\e084'}.oi-link-broken:before{content:'\e085'}.oi-link-intact:before{content:'\e086'}.oi-list-rich:before{content:'\e087'}.oi-list:before{content:'\e088'}.oi-location:before{content:'\e089'}.oi-lock-locked:before{content:'\e08a'}.oi-lock-unlocked:before{content:'\e08b'}.oi-loop-circular:before{content:'\e08c'}.oi-loop-square:before{content:'\e08d'}.oi-loop:before{content:'\e08e'}.oi-magnifying-glass:before{content:'\e08f'}.oi-map-marker:before{content:'\e090'}.oi-map:before{content:'\e091'}.oi-media-pause:before{content:'\e092'}.oi-media-play:before{content:'\e093'}.oi-media-record:before{content:'\e094'}.oi-media-skip-backward:before{content:'\e095'}.oi-media-skip-forward:before{content:'\e096'}.oi-media-step-backward:before{content:'\e097'}.oi-media-step-forward:before{content:'\e098'}.oi-media-stop:before{content:'\e099'}.oi-medical-cross:before{content:'\e09a'}.oi-menu:before{content:'\e09b'}.oi-microphone:before{content:'\e09c'}.oi-minus:before{content:'\e09d'}.oi-monitor:before{content:'\e09e'}.oi-moon:before{content:'\e09f'}.oi-move:before{content:'\e0a0'}.oi-musical-note:before{content:'\e0a1'}.oi-paperclip:before{content:'\e0a2'}.oi-pencil:before{content:'\e0a3'}.oi-people:before{content:'\e0a4'}.oi-person:before{content:'\e0a5'}.oi-phone:before{content:'\e0a6'}.oi-pie-chart:before{content:'\e0a7'}.oi-pin:before{content:'\e0a8'}.oi-play-circle:before{content:'\e0a9'}.oi-plus:before{content:'\e0aa'}.oi-power-standby:before{content:'\e0ab'}.oi-print:before{content:'\e0ac'}.oi-project:before{content:'\e0ad'}.oi-pulse:before{content:'\e0ae'}.oi-puzzle-piece:before{content:'\e0af'}.oi-question-mark:before{content:'\e0b0'}.oi-rain:before{content:'\e0b1'}.oi-random:before{content:'\e0b2'}.oi-reload:before{content:'\e0b3'}.oi-resize-both:before{content:'\e0b4'}.oi-resize-height:before{content:'\e0b5'}.oi-resize-width:before{content:'\e0b6'}.oi-rss-alt:before{content:'\e0b7'}.oi-rss:before{content:'\e0b8'}.oi-script:before{content:'\e0b9'}.oi-share-boxed:before{content:'\e0ba'}.oi-share:before{content:'\e0bb'}.oi-shield:before{content:'\e0bc'}.oi-signal:before{content:'\e0bd'}.oi-signpost:before{content:'\e0be'}.oi-sort-ascending:before{content:'\e0bf'}.oi-sort-descending:before{content:'\e0c0'}.oi-spreadsheet:before{content:'\e0c1'}.oi-star:before{content:'\e0c2'}.oi-sun:before{content:'\e0c3'}.oi-tablet:before{content:'\e0c4'}.oi-tag:before{content:'\e0c5'}.oi-tags:before{content:'\e0c6'}.oi-target:before{content:'\e0c7'}.oi-task:before{content:'\e0c8'}.oi-terminal:before{content:'\e0c9'}.oi-text:before{content:'\e0ca'}.oi-thumb-down:before{content:'\e0cb'}.oi-thumb-up:before{content:'\e0cc'}.oi-timer:before{content:'\e0cd'}.oi-transfer:before{content:'\e0ce'}.oi-trash:before{content:'\e0cf'}.oi-underline:before{content:'\e0d0'}.oi-vertical-align-bottom:before{content:'\e0d1'}.oi-vertical-align-center:before{content:'\e0d2'}.oi-vertical-align-top:before{content:'\e0d3'}.oi-video:before{content:'\e0d4'}.oi-volume-high:before{content:'\e0d5'}.oi-volume-low:before{content:'\e0d6'}.oi-volume-off:before{content:'\e0d7'}.oi-warning:before{content:'\e0d8'}.oi-wifi:before{content:'\e0d9'}.oi-wrench:before{content:'\e0da'}.oi-x:before{content:'\e0db'}.oi-yen:before{content:'\e0dc'}.oi-zoom-in:before{content:'\e0dd'}.oi-zoom-out:before{content:'\e0de'} -------------------------------------------------------------------------------- /wwwroot/fileinput.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | window.BlazorInputFile = { 3 | init: function init(elem, componentInstance) { 4 | elem._blazorInputFileNextFileId = 0; 5 | 6 | elem.addEventListener('change', function handleInputFileChange(event) { 7 | // Reduce to purely serializable data, plus build an index by ID 8 | elem._blazorFilesById = {}; 9 | var fileList = Array.prototype.map.call(elem.files, function (file) { 10 | var result = { 11 | id: ++elem._blazorInputFileNextFileId, 12 | lastModified: new Date(file.lastModified).toISOString(), 13 | name: file.name, 14 | size: file.size, 15 | type: file.type, 16 | relativePath: file.webkitRelativePath 17 | }; 18 | elem._blazorFilesById[result.id] = result; 19 | 20 | // Attach the blob data itself as a non-enumerable property so it doesn't appear in the JSON 21 | Object.defineProperty(result, 'blob', { value: file }); 22 | 23 | return result; 24 | }); 25 | 26 | componentInstance.invokeMethodAsync('NotifyChange', fileList).then(function () { 27 | //reset file value ,otherwise, the same filename will not be trigger change event again 28 | elem.value = ''; 29 | }, function (err) { 30 | //reset file value ,otherwise, the same filename will not be trigger change event again 31 | elem.value = ''; 32 | throw new Error(err); 33 | }); 34 | }); 35 | }, 36 | 37 | toImageFile(elem, fileId, format, maxWidth, maxHeight) { 38 | var originalFile = getFileById(elem, fileId); 39 | 40 | return new Promise(function (resolve) { 41 | var originalFileImage = new Image(); 42 | originalFileImage.onload = function () { resolve(originalFileImage); }; 43 | originalFileImage.src = URL.createObjectURL(originalFile.blob); 44 | }).then(function (loadedImage) { 45 | return new Promise(function (resolve) { 46 | var desiredWidthRatio = Math.min(1, maxWidth / loadedImage.width); 47 | var desiredHeightRatio = Math.min(1, maxHeight / loadedImage.height); 48 | var chosenSizeRatio = Math.min(desiredWidthRatio, desiredHeightRatio); 49 | 50 | var canvas = document.createElement('canvas'); 51 | canvas.width = Math.round(loadedImage.width * chosenSizeRatio); 52 | canvas.height = Math.round(loadedImage.height * chosenSizeRatio); 53 | canvas.getContext('2d').drawImage(loadedImage, 0, 0, canvas.width, canvas.height); 54 | canvas.toBlob(resolve, format); 55 | }); 56 | }).then(function (resizedImageBlob) { 57 | var result = { 58 | id: ++elem._blazorInputFileNextFileId, 59 | lastModified: originalFile.lastModified, 60 | name: originalFile.name, // Note: we're not changing the file extension 61 | size: resizedImageBlob.size, 62 | type: format, 63 | relativePath: originalFile.relativePath 64 | }; 65 | 66 | elem._blazorFilesById[result.id] = result; 67 | 68 | // Attach the blob data itself as a non-enumerable property so it doesn't appear in the JSON 69 | Object.defineProperty(result, 'blob', { value: resizedImageBlob }); 70 | 71 | return result; 72 | }); 73 | }, 74 | 75 | readFileData: function readFileData(elem, fileId, startOffset, count) { 76 | var readPromise = getArrayBufferFromFileAsync(elem, fileId); 77 | 78 | return readPromise.then(function (arrayBuffer) { 79 | var uint8Array = new Uint8Array(arrayBuffer, startOffset, count); 80 | var base64 = uint8ToBase64(uint8Array); 81 | return base64; 82 | }); 83 | }, 84 | 85 | ensureArrayBufferReadyForSharedMemoryInterop: function ensureArrayBufferReadyForSharedMemoryInterop(elem, fileId) { 86 | return getArrayBufferFromFileAsync(elem, fileId).then(function (arrayBuffer) { 87 | getFileById(elem, fileId).arrayBuffer = arrayBuffer; 88 | }); 89 | }, 90 | 91 | readFileDataSharedMemory: function readFileDataSharedMemory(readRequest) { 92 | // This uses various unsupported internal APIs. Beware that if you also use them, 93 | // your code could become broken by any update. 94 | var inputFileElementReferenceId = Blazor.platform.readStringField(readRequest, 0); 95 | var inputFileElement = document.querySelector('[_bl_' + inputFileElementReferenceId + ']'); 96 | var fileId = Blazor.platform.readInt32Field(readRequest, 4); 97 | var sourceOffset = Blazor.platform.readUint64Field(readRequest, 8); 98 | var destination = Blazor.platform.readInt32Field(readRequest, 16); 99 | var destinationOffset = Blazor.platform.readInt32Field(readRequest, 20); 100 | var maxBytes = Blazor.platform.readInt32Field(readRequest, 24); 101 | 102 | var sourceArrayBuffer = getFileById(inputFileElement, fileId).arrayBuffer; 103 | var bytesToRead = Math.min(maxBytes, sourceArrayBuffer.byteLength - sourceOffset); 104 | var sourceUint8Array = new Uint8Array(sourceArrayBuffer, sourceOffset, bytesToRead); 105 | 106 | var destinationUint8Array = Blazor.platform.toUint8Array(destination); 107 | destinationUint8Array.set(sourceUint8Array, destinationOffset); 108 | 109 | return bytesToRead; 110 | } 111 | }; 112 | 113 | function getFileById(elem, fileId) { 114 | var file = elem._blazorFilesById[fileId]; 115 | if (!file) { 116 | throw new Error('There is no file with ID ' + fileId + '. The file list may have changed'); 117 | } 118 | 119 | return file; 120 | } 121 | 122 | function getArrayBufferFromFileAsync(elem, fileId) { 123 | var file = getFileById(elem, fileId); 124 | 125 | // On the first read, convert the FileReader into a Promise 126 | if (!file.readPromise) { 127 | file.readPromise = new Promise(function (resolve, reject) { 128 | var reader = new FileReader(); 129 | reader.onload = function () { resolve(reader.result); }; 130 | reader.onerror = function (err) { reject(err); }; 131 | reader.readAsArrayBuffer(file.blob); 132 | }); 133 | } 134 | 135 | return file.readPromise; 136 | } 137 | 138 | var uint8ToBase64 = (function () { 139 | // Code from https://github.com/beatgammit/base64-js/ 140 | // License: MIT 141 | var lookup = []; 142 | 143 | var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 144 | for (var i = 0, len = code.length; i < len; ++i) { 145 | lookup[i] = code[i]; 146 | } 147 | 148 | function tripletToBase64(num) { 149 | return lookup[num >> 18 & 0x3F] + 150 | lookup[num >> 12 & 0x3F] + 151 | lookup[num >> 6 & 0x3F] + 152 | lookup[num & 0x3F]; 153 | } 154 | 155 | function encodeChunk(uint8, start, end) { 156 | var tmp; 157 | var output = []; 158 | for (var i = start; i < end; i += 3) { 159 | tmp = 160 | ((uint8[i] << 16) & 0xFF0000) + 161 | ((uint8[i + 1] << 8) & 0xFF00) + 162 | (uint8[i + 2] & 0xFF); 163 | output.push(tripletToBase64(tmp)); 164 | } 165 | return output.join(''); 166 | } 167 | 168 | return function fromByteArray(uint8) { 169 | var tmp; 170 | var len = uint8.length; 171 | var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes 172 | var parts = []; 173 | var maxChunkLength = 16383; // must be multiple of 3 174 | 175 | // go through the array every three bytes, we'll deal with trailing stuff later 176 | for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { 177 | parts.push(encodeChunk( 178 | uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) 179 | )); 180 | } 181 | 182 | // pad the end with zeros, but make sure to not forget the extra bytes 183 | if (extraBytes === 1) { 184 | tmp = uint8[len - 1]; 185 | parts.push( 186 | lookup[tmp >> 2] + 187 | lookup[(tmp << 4) & 0x3F] + 188 | '==' 189 | ); 190 | } else if (extraBytes === 2) { 191 | tmp = (uint8[len - 2] << 8) + uint8[len - 1]; 192 | parts.push( 193 | lookup[tmp >> 10] + 194 | lookup[(tmp >> 4) & 0x3F] + 195 | lookup[(tmp << 2) & 0x3F] + 196 | '=' 197 | ); 198 | } 199 | 200 | return parts.join(''); 201 | }; 202 | })(); 203 | })(); -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome:http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Don't use tabs for indentation. 7 | [*] 8 | indent_style = space 9 | 10 | # Code files 11 | [*.cs] 12 | indent_size = 4 13 | insert_final_newline = true 14 | charset = utf-8-bom 15 | 16 | # Xml project files 17 | [*.csproj] 18 | indent_size = 2 19 | 20 | # Xml config files 21 | [*.{props,targets}] 22 | indent_size = 2 23 | 24 | # Dotnet code style settings: 25 | [*.cs] 26 | # Sort using and Import directives with System.* appearing first 27 | dotnet_sort_system_directives_first = true 28 | dotnet_style_require_accessibility_modifiers = always:warning 29 | 30 | # No blank line between System.* and Microsoft.* 31 | dotnet_separate_import_directive_groups = false 32 | 33 | # Suggest more modern language features when available 34 | dotnet_style_object_initializer = true:suggestion 35 | dotnet_style_collection_initializer = true:suggestion 36 | dotnet_style_coalesce_expression = true:error 37 | dotnet_style_null_propagation = true:error 38 | dotnet_style_explicit_tuple_names = true:suggestion 39 | dotnet_style_prefer_inferred_tuple_names = true:suggestion 40 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion 41 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion 42 | dotnet_style_prefer_conditional_expression_over_return = false 43 | dotnet_style_prefer_conditional_expression_over_assignment = false 44 | dotnet_style_prefer_auto_properties = false 45 | 46 | # Avoid "this." and "Me." if not necessary 47 | dotnet_style_qualification_for_field = false:error 48 | dotnet_style_qualification_for_property = true:error 49 | dotnet_style_qualification_for_method = false:error 50 | dotnet_style_qualification_for_event = false:error 51 | 52 | # Use language keywords instead of framework type names for type references 53 | dotnet_style_predefined_type_for_locals_parameters_members = true:error 54 | dotnet_style_predefined_type_for_member_access = true:error 55 | 56 | # Prefer read-only on fields 57 | dotnet_style_readonly_field = true:warning 58 | 59 | # Naming Rules 60 | dotnet_naming_rule.interfaces_must_be_pascal_cased_and_prefixed_with_I.symbols = interface_symbols 61 | dotnet_naming_rule.interfaces_must_be_pascal_cased_and_prefixed_with_I.style = pascal_case_and_prefix_with_I_style 62 | dotnet_naming_rule.interfaces_must_be_pascal_cased_and_prefixed_with_I.severity = warning 63 | 64 | dotnet_naming_rule.externally_visible_members_must_be_pascal_cased.symbols = externally_visible_symbols 65 | dotnet_naming_rule.externally_visible_members_must_be_pascal_cased.style = pascal_case_style 66 | dotnet_naming_rule.externally_visible_members_must_be_pascal_cased.severity = warning 67 | 68 | dotnet_naming_rule.parameters_must_be_camel_cased.symbols = parameter_symbols 69 | dotnet_naming_rule.parameters_must_be_camel_cased.style = camel_case_style 70 | dotnet_naming_rule.parameters_must_be_camel_cased.severity = warning 71 | 72 | dotnet_naming_rule.constants_must_be_pascal_cased.symbols = constant_symbols 73 | dotnet_naming_rule.constants_must_be_pascal_cased.style = pascal_case_style 74 | dotnet_naming_rule.constants_must_be_pascal_cased.severity = warning 75 | 76 | dotnet_naming_rule.private_static_fields_must_be_camel_cased_and_prefixed_with_s_underscore.symbols = private_static_field_symbols 77 | dotnet_naming_rule.private_static_fields_must_be_camel_cased_and_prefixed_with_s_underscore.style = camel_case_and_prefix_with_s_underscore_style 78 | dotnet_naming_rule.private_static_fields_must_be_camel_cased_and_prefixed_with_s_underscore.severity = warning 79 | 80 | dotnet_naming_rule.private_instance_fields_must_be_camel_cased_and_prefixed_with_underscore.symbols = private_field_symbols 81 | dotnet_naming_rule.private_instance_fields_must_be_camel_cased_and_prefixed_with_underscore.style = camel_case_and_prefix_with_underscore_style 82 | dotnet_naming_rule.private_instance_fields_must_be_camel_cased_and_prefixed_with_underscore.severity = warning 83 | 84 | # Symbols 85 | dotnet_naming_symbols.externally_visible_symbols.applicable_kinds = class,struct,interface,enum,property,method,field,event,delegate 86 | dotnet_naming_symbols.externally_visible_symbols.applicable_accessibilities = public,internal,friend,protected,protected_internal,protected_friend,private_protected 87 | 88 | dotnet_naming_symbols.interface_symbols.applicable_kinds = interface 89 | dotnet_naming_symbols.interface_symbols.applicable_accessibilities = * 90 | 91 | dotnet_naming_symbols.parameter_symbols.applicable_kinds = parameter 92 | dotnet_naming_symbols.parameter_symbols.applicable_accessibilities = * 93 | 94 | dotnet_naming_symbols.constant_symbols.applicable_kinds = field 95 | dotnet_naming_symbols.constant_symbols.required_modifiers = const 96 | dotnet_naming_symbols.constant_symbols.applicable_accessibilities = * 97 | 98 | dotnet_naming_symbols.private_static_field_symbols.applicable_kinds = field 99 | dotnet_naming_symbols.private_static_field_symbols.required_modifiers = static,shared 100 | dotnet_naming_symbols.private_static_field_symbols.applicable_accessibilities = private 101 | 102 | dotnet_naming_symbols.private_field_symbols.applicable_kinds = field 103 | dotnet_naming_symbols.private_field_symbols.applicable_accessibilities = private 104 | 105 | # Styles 106 | dotnet_naming_style.camel_case_style.capitalization = camel_case 107 | 108 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case 109 | 110 | dotnet_naming_style.camel_case_and_prefix_with_s_underscore_style.required_prefix = s_ 111 | dotnet_naming_style.camel_case_and_prefix_with_s_underscore_style.capitalization = camel_case 112 | 113 | dotnet_naming_style.camel_case_and_prefix_with_underscore_style.required_prefix = _ 114 | dotnet_naming_style.camel_case_and_prefix_with_underscore_style.capitalization = camel_case 115 | 116 | dotnet_naming_style.pascal_case_and_prefix_with_I_style.required_prefix = I 117 | dotnet_naming_style.pascal_case_and_prefix_with_I_style.capitalization = pascal_case 118 | 119 | # CSharp code style settings: 120 | # Prefer "var" only when the type is apparent 121 | csharp_style_var_for_built_in_types = false:suggestion 122 | csharp_style_var_when_type_is_apparent = true:suggestion 123 | csharp_style_var_elsewhere = false:suggestion 124 | 125 | # Prefer method-like constructs to have a block body 126 | csharp_style_expression_bodied_methods = false:none 127 | csharp_style_expression_bodied_constructors = false:none 128 | csharp_style_expression_bodied_operators = false:none 129 | 130 | # Prefer property-like constructs to have an expression-body 131 | csharp_style_expression_bodied_properties = true:none 132 | csharp_style_expression_bodied_indexers = true:none 133 | csharp_style_expression_bodied_accessors = true:none 134 | 135 | # Suggest more modern language features when available 136 | csharp_style_pattern_matching_over_is_with_cast_check = true:error 137 | csharp_style_pattern_matching_over_as_with_null_check = true:error 138 | csharp_style_inlined_variable_declaration = true:error 139 | csharp_style_throw_expression = true:suggestion 140 | csharp_style_conditional_delegate_call = true:suggestion 141 | csharp_style_deconstructed_variable_declaration = true:suggestion 142 | 143 | # Newline settings 144 | csharp_new_line_before_open_brace = all 145 | csharp_new_line_before_else = true 146 | csharp_new_line_before_catch = true 147 | csharp_new_line_before_finally = true 148 | csharp_new_line_before_members_in_object_initializers = true 149 | csharp_new_line_before_members_in_anonymous_types = true 150 | csharp_new_line_between_query_expression_clauses = true 151 | 152 | # Identation options 153 | csharp_indent_case_contents = true 154 | csharp_indent_case_contents_when_block = true 155 | csharp_indent_switch_labels = true 156 | csharp_indent_labels = no_change 157 | csharp_indent_block_contents = true 158 | csharp_indent_braces = false 159 | 160 | # Spacing options 161 | csharp_space_after_cast = false 162 | csharp_space_after_keywords_in_control_flow_statements = true 163 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 164 | csharp_space_between_method_call_parameter_list_parentheses = false 165 | csharp_space_between_method_call_name_and_opening_parenthesis = false 166 | csharp_space_between_method_declaration_parameter_list_parentheses = false 167 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 168 | csharp_space_between_method_declaration_parameter_list_parentheses = false 169 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 170 | csharp_space_between_parentheses = false 171 | csharp_space_between_square_brackets = false 172 | csharp_space_between_empty_square_brackets = false 173 | csharp_space_before_open_square_brackets = false 174 | csharp_space_around_declaration_statements = false 175 | csharp_space_around_binary_operators = before_and_after 176 | csharp_space_after_cast = false 177 | csharp_space_before_semicolon_in_for_statement = false 178 | csharp_space_before_dot = false 179 | csharp_space_after_dot = false 180 | csharp_space_before_comma = false 181 | csharp_space_after_comma = true 182 | csharp_space_before_colon_in_inheritance_clause = true 183 | csharp_space_after_colon_in_inheritance_clause = true 184 | csharp_space_after_semicolon_in_for_statement = true 185 | 186 | # Wrapping 187 | csharp_preserve_single_line_statements = true 188 | csharp_preserve_single_line_blocks = true 189 | 190 | # Code block 191 | csharp_prefer_braces = when_multiline:error 192 | 193 | # CA1303: Do not pass literals as localized parameters 194 | dotnet_diagnostic.CA1303.severity = none 195 | 196 | # CA1812: GameBoard is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it static (Shared in Visual Basic). 197 | dotnet_diagnostic.CA1812.severity = none 198 | 199 | # CA1707: Identifiers should not contain underscores 200 | dotnet_diagnostic.CA1707.severity = none 201 | 202 | # CA1062: Validate arguments of public methods 203 | dotnet_diagnostic.CA1062.severity = none 204 | 205 | # IDE0005: Using directive is unnecessary. 206 | dotnet_diagnostic.IDE0005.severity = error 207 | 208 | # CA1710: Identifiers should have correct suffix 209 | dotnet_diagnostic.CA1710.severity = none 210 | 211 | # Don't use keywords 212 | dotnet_diagnostic.CA1716.severity = none 213 | 214 | # CA1063: Implement IDisposable Correctly 215 | dotnet_diagnostic.CA1063.severity = none 216 | 217 | # CA1816: Dispose methods should call SuppressFinalize 218 | dotnet_diagnostic.CA1816.severity = none 219 | 220 | # CA1305: Specify IFormatProvider 221 | dotnet_diagnostic.CA1305.severity = none 222 | 223 | # CA1308: Normalize strings to uppercase 224 | dotnet_diagnostic.CA1308.severity = none 225 | 226 | # IDE0054: Use compound assignment 227 | dotnet_style_prefer_compound_assignment = false:suggestion 228 | 229 | # CA1307: Specify StringComparison 230 | dotnet_diagnostic.CA1307.severity = none 231 | 232 | # CA1030: Use events where appropriate 233 | dotnet_diagnostic.CA1030.severity = none 234 | 235 | # CA1724: Type names should not match namespaces 236 | dotnet_diagnostic.CA1724.severity = none 237 | -------------------------------------------------------------------------------- /Samples/Dependency Injection.Generator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Microsoft.CodeAnalysis; 6 | using Microsoft.CodeAnalysis.CSharp; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | using Microsoft.CodeAnalysis.Text; 9 | 10 | namespace SourceGenerator 11 | { 12 | [Generator] 13 | public class DISourceGenerator : ISourceGenerator 14 | { 15 | private const bool SimplifyFieldNames = true; 16 | private const bool UseLazyWhenMultipleServices = true; 17 | 18 | private const string ServiceLocatorStub = @" 19 | namespace DI 20 | { 21 | public static class ServiceLocator 22 | { 23 | public static T GetService() 24 | { 25 | return default; 26 | } 27 | } 28 | } 29 | "; 30 | private const string TransientAttribute = @" 31 | using System; 32 | 33 | namespace DI 34 | { 35 | [AttributeUsage(AttributeTargets.Interface)] 36 | public class TransientAttribute : Attribute 37 | { 38 | } 39 | } 40 | "; 41 | 42 | public void Initialize(GeneratorInitializationContext context) 43 | { 44 | } 45 | 46 | public void Execute(GeneratorExecutionContext context) 47 | { 48 | Compilation? compilation = context.Compilation; 49 | 50 | compilation = GenerateHelperClasses(context); 51 | 52 | INamedTypeSymbol? serviceLocatorClass = compilation.GetTypeByMetadataName("DI.ServiceLocator")!; 53 | INamedTypeSymbol? transientAttribute = compilation.GetTypeByMetadataName("DI.TransientAttribute")!; 54 | 55 | INamedTypeSymbol? iEnumerableOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1")!.ConstructUnboundGenericType(); 56 | INamedTypeSymbol? listOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1")!; 57 | 58 | var knownTypes = new KnownTypes(iEnumerableOfT, listOfT, transientAttribute); 59 | 60 | var services = new List(); 61 | foreach (SyntaxTree? tree in compilation.SyntaxTrees) 62 | { 63 | SemanticModel? semanticModel = compilation.GetSemanticModel(tree); 64 | IEnumerable? typesToCreate = from i in tree.GetRoot().DescendantNodesAndSelf().OfType() 65 | let symbol = semanticModel.GetSymbolInfo(i).Symbol as IMethodSymbol 66 | where symbol != null 67 | where SymbolEqualityComparer.Default.Equals(symbol.ContainingType, serviceLocatorClass) 68 | select symbol.ReturnType as INamedTypeSymbol; 69 | 70 | foreach (INamedTypeSymbol? typeToCreate in typesToCreate) 71 | { 72 | CollectServices(context, typeToCreate, compilation, services, knownTypes); 73 | } 74 | } 75 | 76 | GenerateServiceLocator(context, services); 77 | } 78 | 79 | private static Compilation GenerateHelperClasses(GeneratorExecutionContext context) 80 | { 81 | var compilation = context.Compilation; 82 | 83 | var options = (compilation as CSharpCompilation)?.SyntaxTrees[0].Options as CSharpParseOptions; 84 | var tempCompilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(ServiceLocatorStub, Encoding.UTF8), options)) 85 | .AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(TransientAttribute, Encoding.UTF8), options)); 86 | 87 | context.AddSource("TransientAttribute.cs", TransientAttribute); 88 | 89 | return tempCompilation; 90 | } 91 | 92 | private static void GenerateServiceLocator(GeneratorExecutionContext context, List services) 93 | { 94 | var sourceBuilder = new StringBuilder(); 95 | 96 | bool generateLazies = UseLazyWhenMultipleServices && services.Count > 1; 97 | 98 | sourceBuilder.AppendLine(@" 99 | using System; 100 | 101 | namespace DI 102 | { 103 | public static class ServiceLocator 104 | {"); 105 | var fields = new List(); 106 | GenerateFields(sourceBuilder, services, fields, generateLazies); 107 | 108 | sourceBuilder.AppendLine(@" 109 | public static T GetService() 110 | {"); 111 | 112 | foreach (Service? service in services) 113 | { 114 | if (service != services.Last()) 115 | { 116 | sourceBuilder.AppendLine("if (typeof(T) == typeof(" + service.Type + "))"); 117 | sourceBuilder.AppendLine("{"); 118 | } 119 | sourceBuilder.AppendLine($" return (T)(object){GetTypeConstruction(service, service.IsTransient ? new List() : fields, !service.IsTransient && generateLazies)};"); 120 | if (service != services.Last()) 121 | { 122 | sourceBuilder.AppendLine("}"); 123 | } 124 | } 125 | 126 | if (services.Count == 0) 127 | { 128 | sourceBuilder.AppendLine("throw new System.InvalidOperationException(\"This code is unreachable.\");"); 129 | } 130 | sourceBuilder.AppendLine(@" 131 | } 132 | } 133 | }"); 134 | 135 | context.AddSource("ServiceLocator.cs", sourceBuilder.ToString()); 136 | } 137 | 138 | private static void GenerateFields(StringBuilder sourceBuilder, List services, List fields, bool lazy) 139 | { 140 | foreach (Service? service in services) 141 | { 142 | GenerateFields(sourceBuilder, service.ConstructorArguments, fields, lazy); 143 | if (!service.IsTransient) 144 | { 145 | if (fields.Any(f => SymbolEqualityComparer.Default.Equals(f.ImplementationType, service.ImplementationType))) 146 | { 147 | continue; 148 | } 149 | service.VariableName = GetVariableName(service, fields); 150 | sourceBuilder.Append($"private static "); 151 | if (lazy) 152 | { 153 | sourceBuilder.Append("Lazy<"); 154 | } 155 | sourceBuilder.Append(service.Type); 156 | if (lazy) 157 | { 158 | sourceBuilder.Append(">"); 159 | } 160 | sourceBuilder.AppendLine($" {service.VariableName} = {GetTypeConstruction(service, fields, lazy)};"); 161 | fields.Add(service); 162 | } 163 | } 164 | } 165 | 166 | private static string GetTypeConstruction(Service service, List fields, bool lazy) 167 | { 168 | var sb = new StringBuilder(); 169 | 170 | Service? field = fields.FirstOrDefault(f => SymbolEqualityComparer.Default.Equals(f.ImplementationType, service.ImplementationType)); 171 | if (field != null) 172 | { 173 | sb.Append(field.VariableName); 174 | if (lazy) 175 | { 176 | sb.Append(".Value"); 177 | } 178 | } 179 | else 180 | { 181 | if (lazy) 182 | { 183 | sb.Append("new Lazy<"); 184 | sb.Append(service.Type); 185 | sb.Append(">(() => "); 186 | } 187 | sb.Append("new "); 188 | sb.Append(service.ImplementationType); 189 | sb.Append('('); 190 | if (service.UseCollectionInitializer) 191 | { 192 | sb.Append(')'); 193 | sb.Append('{'); 194 | } 195 | bool first = true; 196 | foreach (Service? arg in service.ConstructorArguments) 197 | { 198 | if (!first) 199 | { 200 | sb.Append(','); 201 | } 202 | sb.Append(GetTypeConstruction(arg, fields, lazy)); 203 | first = false; 204 | } 205 | if (service.UseCollectionInitializer) 206 | { 207 | sb.Append('}'); 208 | } 209 | else 210 | { 211 | sb.Append(')'); 212 | } 213 | if (lazy) 214 | { 215 | sb.Append(")"); 216 | } 217 | } 218 | return sb.ToString(); 219 | } 220 | 221 | private static string GetVariableName(Service service, List fields) 222 | { 223 | string typeName = service.ImplementationType.ToString().Replace("<", "").Replace(">", "").Replace("?", ""); 224 | 225 | string[] parts = typeName.Split('.'); 226 | for (int i = parts.Length - 1; i >= 0; i--) 227 | { 228 | string? candidate = string.Join("", parts.Skip(i)); 229 | candidate = "_" + char.ToLowerInvariant(candidate[0]) + candidate.Substring(1); 230 | if (!fields.Any(f => string.Equals(f.VariableName, candidate, StringComparison.Ordinal))) 231 | { 232 | typeName = candidate; 233 | if (SimplifyFieldNames) 234 | { 235 | break; 236 | } 237 | } 238 | } 239 | return typeName; 240 | } 241 | 242 | private static void CollectServices(GeneratorExecutionContext context, INamedTypeSymbol typeToCreate, Compilation compilation, List services, KnownTypes knownTypes) 243 | { 244 | typeToCreate = (INamedTypeSymbol)typeToCreate.WithNullableAnnotation(default); 245 | 246 | if (services.Any(s => SymbolEqualityComparer.Default.Equals(s.Type, typeToCreate))) 247 | { 248 | return; 249 | } 250 | 251 | if (typeToCreate.IsGenericType && SymbolEqualityComparer.Default.Equals(typeToCreate.ConstructUnboundGenericType(), knownTypes.IEnumerableOfT)) 252 | { 253 | ITypeSymbol? typeToFind = typeToCreate.TypeArguments[0]; 254 | IEnumerable? types = FindImplementations(typeToFind, compilation); 255 | 256 | INamedTypeSymbol? list = knownTypes.ListOfT.Construct(typeToFind); 257 | 258 | var listService = new Service(typeToCreate); 259 | services.Add(listService); 260 | listService.ImplementationType = list; 261 | listService.UseCollectionInitializer = true; 262 | 263 | foreach (INamedTypeSymbol? thingy in types) 264 | { 265 | CollectServices(context, thingy, compilation, listService.ConstructorArguments, knownTypes); 266 | } 267 | } 268 | else 269 | { 270 | INamedTypeSymbol? realType = typeToCreate.IsAbstract ? FindImplementation(typeToCreate, compilation) : typeToCreate; 271 | 272 | if (realType == null) 273 | { 274 | context.ReportDiagnostic(Diagnostic.Create(new DiagnosticDescriptor("DIGEN001", "Type not found", $"Could not find an implementation of '{typeToCreate}'.", "DI.ServiceLocator", DiagnosticSeverity.Error, true), Location.None)); 275 | return; 276 | } 277 | 278 | var service = new Service(typeToCreate); 279 | services.Add(service); 280 | service.ImplementationType = realType; 281 | service.IsTransient = typeToCreate.GetAttributes().Any(c => SymbolEqualityComparer.Default.Equals(c.AttributeClass, knownTypes.TransientAttribute)); 282 | 283 | IMethodSymbol? constructor = realType?.Constructors.FirstOrDefault(); 284 | if (constructor != null) 285 | { 286 | foreach (IParameterSymbol? parametr in constructor.Parameters) 287 | { 288 | if (parametr.Type is INamedTypeSymbol paramType) 289 | { 290 | CollectServices(context, paramType, compilation, service.ConstructorArguments, knownTypes); 291 | } 292 | } 293 | } 294 | } 295 | } 296 | 297 | private static INamedTypeSymbol? FindImplementation(ITypeSymbol typeToCreate, Compilation compilation) 298 | { 299 | return FindImplementations(typeToCreate, compilation).FirstOrDefault(); 300 | } 301 | 302 | private static IEnumerable FindImplementations(ITypeSymbol typeToFind, Compilation compilation) 303 | { 304 | foreach (INamedTypeSymbol? x in GetAllTypes(compilation.GlobalNamespace.GetNamespaceMembers())) 305 | { 306 | if (!x.IsAbstract && x.Interfaces.Any(i => SymbolEqualityComparer.Default.Equals(i, typeToFind))) 307 | { 308 | yield return x; 309 | } 310 | } 311 | } 312 | 313 | private static IEnumerable GetAllTypes(IEnumerable namespaces) 314 | { 315 | foreach (INamespaceSymbol? ns in namespaces) 316 | { 317 | foreach (INamedTypeSymbol? t in ns.GetTypeMembers()) 318 | { 319 | yield return t; 320 | } 321 | 322 | foreach (INamedTypeSymbol? subType in GetAllTypes(ns.GetNamespaceMembers())) 323 | { 324 | yield return subType; 325 | } 326 | } 327 | } 328 | 329 | private class KnownTypes 330 | { 331 | public INamedTypeSymbol IEnumerableOfT; 332 | public INamedTypeSymbol ListOfT; 333 | public INamedTypeSymbol TransientAttribute; 334 | 335 | public KnownTypes(INamedTypeSymbol iEnumerableOfT, INamedTypeSymbol listOfT, INamedTypeSymbol transientAttribute) 336 | { 337 | IEnumerableOfT = iEnumerableOfT; 338 | ListOfT = listOfT; 339 | TransientAttribute = transientAttribute; 340 | } 341 | } 342 | 343 | private class Service 344 | { 345 | public Service(INamedTypeSymbol typeToCreate) 346 | { 347 | this.Type = typeToCreate; 348 | } 349 | 350 | public INamedTypeSymbol Type { get; set; } 351 | public INamedTypeSymbol ImplementationType { get; internal set; } = null!; 352 | public List ConstructorArguments { get; internal set; } = new List(); 353 | public bool IsTransient { get; internal set; } 354 | public bool UseCollectionInitializer { get; internal set; } 355 | public string? VariableName { get; internal set; } 356 | } 357 | } 358 | } 359 | -------------------------------------------------------------------------------- /Runner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Immutable; 4 | using System.Diagnostics.CodeAnalysis; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Net.Http; 8 | using System.Reflection; 9 | using System.Text; 10 | using System.Threading; 11 | using System.Threading.Tasks; 12 | using Microsoft.AspNetCore.Components; 13 | using Microsoft.CodeAnalysis; 14 | using Microsoft.CodeAnalysis.CSharp; 15 | using MonoTouch.Dialog.Utilities; 16 | 17 | #nullable enable 18 | 19 | namespace SourceGeneratorPlayground 20 | { 21 | internal class Runner : IRunner 22 | { 23 | private static readonly Dictionary? s_references = new(); 24 | 25 | private static readonly LRUCache> s_sourceGeneratorCache = new(entryLimit: 10); 26 | 27 | private readonly string _baseUri; 28 | 29 | public string ErrorText { get; private set; } = ""; 30 | public string? GeneratorOutput { get; private set; } = ""; 31 | public string ProgramOutput { get; private set; } = ""; 32 | 33 | public Runner(NavigationManager navigationManager) 34 | { 35 | _baseUri = navigationManager.BaseUri; 36 | } 37 | 38 | public async Task RunAsync(string code, string generator, CancellationToken cancellationToken) 39 | { 40 | await UpdateReferences(_baseUri); 41 | 42 | this.ProgramOutput = ""; 43 | this.GeneratorOutput = ""; 44 | this.ErrorText = ""; 45 | 46 | if (!TryCompileGenerator(generator, out var errorCompilingGenerator, out var generatorInstances, cancellationToken)) 47 | { 48 | this.ErrorText = errorCompilingGenerator; 49 | return; 50 | } 51 | 52 | if (!TryCompileUserCode(code, generatorInstances, out var errorCompilingUserCode, out var programAssembly, out var generatorOutput, cancellationToken)) 53 | { 54 | this.ErrorText = errorCompilingUserCode; 55 | this.GeneratorOutput = generatorOutput; 56 | return; 57 | } 58 | 59 | this.GeneratorOutput = generatorOutput; 60 | var (success, output) = await TryExecuteProgramAsync(programAssembly); 61 | if (!success) 62 | { 63 | this.ErrorText = output; 64 | } 65 | else 66 | { 67 | this.ProgramOutput = output; 68 | } 69 | } 70 | 71 | private static bool TryCompileGenerator( 72 | string code, 73 | [NotNullWhen(false)] out string? error, 74 | [NotNullWhen(true)] out ImmutableArray generators, 75 | CancellationToken cancellationToken) 76 | { 77 | error = default; 78 | generators = default; 79 | 80 | if (string.IsNullOrWhiteSpace(code)) 81 | { 82 | error = "Need more input for the generator code!"; 83 | return false; 84 | } 85 | 86 | var normalizedCode = CSharpSyntaxTree.ParseText(code).GetRoot().NormalizeWhitespace().ToFullString(); 87 | var cacheHit = s_sourceGeneratorCache[normalizedCode]; 88 | if (cacheHit != null) 89 | { 90 | generators = cacheHit; 91 | return true; 92 | } 93 | 94 | var generatorTree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(kind: SourceCodeKind.Regular), "Generator.cs", cancellationToken: cancellationToken); 95 | 96 | var generatorCompilation = CSharpCompilation.Create("Generator", new[] { generatorTree }, s_references.Values, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); 97 | 98 | error = GetErrors("Error(s) compiling generator:", generatorCompilation.GetDiagnostics(cancellationToken: cancellationToken)); 99 | if (error != null) 100 | { 101 | return false; 102 | } 103 | 104 | var generatorAssembly = GetAssembly(generatorCompilation, "generator", out error, cancellationToken: cancellationToken); 105 | if (error != null) 106 | { 107 | return false; 108 | } 109 | if (generatorAssembly == null) 110 | { 111 | error = "Unknown error emitting generator."; 112 | return false; 113 | } 114 | 115 | 116 | generators = generatorAssembly.GetTypes() 117 | .Where(t => !t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsAbstract && !t.GetTypeInfo().ContainsGenericParameters) 118 | .Where(t => typeof(ISourceGenerator).IsAssignableFrom(t)) 119 | .Select(t => Activator.CreateInstance(t)) 120 | .OfType() 121 | .ToImmutableArray(); 122 | 123 | if (generators.Length == 0) 124 | { 125 | error = "Could not instantiate source generator. Types in assembly:" + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, (object)generatorAssembly.GetTypes()); 126 | return false; 127 | } 128 | 129 | s_sourceGeneratorCache[normalizedCode] = generators; 130 | return true; 131 | } 132 | 133 | private static bool TryCompileUserCode 134 | (string code, 135 | ImmutableArray generators, 136 | [NotNullWhen(false)] out string? error, 137 | [NotNullWhen(true)] out Assembly? programAssembly, 138 | out string? generatorOutput, CancellationToken cancellationToken) 139 | { 140 | error = default; 141 | programAssembly = default; 142 | generatorOutput = default; 143 | 144 | if (string.IsNullOrWhiteSpace(code)) 145 | { 146 | error = "Need more input for the user code!"; 147 | return false; 148 | } 149 | 150 | var codeTree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(kind: SourceCodeKind.Regular), "Program.cs", cancellationToken: cancellationToken); 151 | var codeCompilation = CSharpCompilation.Create("Program", new SyntaxTree[] { codeTree }, s_references.Values, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); 152 | 153 | var driver = CSharpGeneratorDriver.Create(generators); 154 | 155 | driver.RunGeneratorsAndUpdateCompilation(codeCompilation, out Compilation? outputCompilation, out ImmutableArray diagnostics, cancellationToken: cancellationToken); 156 | 157 | error = GetErrors("Error(s) running generator:", diagnostics, false); 158 | if (error != null) 159 | { 160 | return false; 161 | } 162 | 163 | var output = new StringBuilder(); 164 | var trees = outputCompilation.SyntaxTrees.Where(t => t != codeTree).OrderBy(t => t.FilePath).ToArray(); 165 | foreach (var tree in trees) 166 | { 167 | if (output.Length > 0) 168 | { 169 | output.AppendLine().AppendLine(); 170 | } 171 | 172 | if (trees.Length > 1) 173 | { 174 | output.AppendLine(tree.FilePath); 175 | output.AppendLine(new string('-', 50)); 176 | } 177 | 178 | output.AppendLine(tree.WithRootAndOptions(tree.GetRoot(cancellationToken: cancellationToken).NormalizeWhitespace(), tree.Options).ToString()); 179 | } 180 | if (output.Length == 0) 181 | { 182 | output.AppendLine("< No source generated >"); 183 | } 184 | generatorOutput = output.ToString(); 185 | 186 | error = GetErrors("Error(s) compiling program:", outputCompilation.GetDiagnostics(cancellationToken: cancellationToken)); 187 | if (error != null) 188 | { 189 | return false; 190 | } 191 | 192 | programAssembly = GetAssembly(outputCompilation, "program", out error, cancellationToken: cancellationToken); 193 | if (error != null) 194 | { 195 | return false; 196 | } 197 | if (programAssembly == null) 198 | { 199 | error = "Unknown error emitting program."; 200 | return false; 201 | } 202 | return true; 203 | } 204 | 205 | private static async Task<(bool Success, string Output)> TryExecuteProgramAsync(Assembly programAssembly) 206 | { 207 | string? error = default; 208 | string? output = default; 209 | var program = programAssembly.GetTypes().FirstOrDefault(t => t.Name == "Program"); 210 | if (program == null) 211 | { 212 | error = "Error executing program:" + Environment.NewLine + Environment.NewLine + "Could not find type \"Program\" in program."; 213 | return (Success: false, Output: error); 214 | } 215 | 216 | var main = program.GetMethod("Main", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); 217 | if (main == null) 218 | { 219 | error = "Error executing program:" + Environment.NewLine + Environment.NewLine + "Could not find static method \"Main\" in program."; 220 | return (Success: false, Output: error); 221 | } 222 | 223 | using var writer = new StringWriter(); 224 | try 225 | { 226 | Console.SetOut(writer); 227 | 228 | int paramCount = main.GetParameters().Length; 229 | if (main.ReturnType == typeof(void)) 230 | { 231 | if (paramCount == 1) 232 | { 233 | main.Invoke(null, new object?[] { null }); 234 | } 235 | else if (paramCount == 0) 236 | { 237 | main.Invoke(null, null); 238 | } 239 | else 240 | { 241 | error = "Error executing program:" + Environment.NewLine + Environment.NewLine + "Method \"Main\" must have 0 or 1 parameters."; 242 | return (Success: false, Output: error); 243 | } 244 | } 245 | else if (main.ReturnType == typeof(Task)) 246 | { 247 | if (paramCount == 1) 248 | { 249 | var task = main.Invoke(null, new object?[] { null }) as Task; 250 | await task!; 251 | } 252 | else if (paramCount == 0) 253 | { 254 | var task = main.Invoke(null, null) as Task; 255 | await task!; 256 | } 257 | else 258 | { 259 | error = "Error executing program:" + Environment.NewLine + Environment.NewLine + "Method \"Main\" must have 0 or 1 parameters."; 260 | return (Success: false, Output: error); 261 | } 262 | } 263 | else 264 | { 265 | error = "Error executing program:" + Environment.NewLine + Environment.NewLine + "Method \"Main\" must have either void or Task return type."; 266 | return (Success: false, Output: error); 267 | } 268 | 269 | output = writer.ToString(); 270 | 271 | if (string.IsNullOrEmpty(output)) 272 | { 273 | output = "< No program output >"; 274 | } 275 | } 276 | catch (Exception ex) 277 | { 278 | error = writer.ToString() + "\n\nError executing program:" + Environment.NewLine + Environment.NewLine + ex.ToString(); 279 | return (Success: false, Output: error); 280 | } 281 | return (Success: true, Output: output); 282 | } 283 | 284 | private static Assembly? GetAssembly(Compilation generatorCompilation, string name, out string? errors, CancellationToken cancellationToken) 285 | { 286 | try 287 | { 288 | using var generatorStream = new MemoryStream(); 289 | var result = generatorCompilation.Emit(generatorStream, cancellationToken: cancellationToken); 290 | if (result == null) 291 | { 292 | errors = "Failed to compile with unknown error"; 293 | return null; 294 | } 295 | if (!result.Success) 296 | { 297 | errors = GetErrors($"Error emitting {name}:", result.Diagnostics, false); 298 | return null; 299 | } 300 | generatorStream.Seek(0, SeekOrigin.Begin); 301 | errors = null; 302 | return Assembly.Load(generatorStream.ToArray()); 303 | } 304 | catch (Exception ex) 305 | { 306 | errors = ex.ToString(); 307 | return null; 308 | } 309 | } 310 | 311 | private static string? GetErrors(string header, IEnumerable diagnostics, bool errorsOnly = true) 312 | { 313 | IEnumerable? errors = diagnostics.Where(d => !errorsOnly || d.Severity == DiagnosticSeverity.Error); 314 | 315 | if (!errors.Any()) 316 | { 317 | return null; 318 | } 319 | 320 | return header + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, errors); 321 | } 322 | 323 | private static async Task> GetReferences(string baseUri) 324 | { 325 | Assembly[]? refs = AppDomain.CurrentDomain.GetAssemblies(); 326 | var client = new HttpClient 327 | { 328 | BaseAddress = new Uri(baseUri) 329 | }; 330 | 331 | var references = new List(); 332 | 333 | foreach (Assembly? reference in refs.Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location))) 334 | { 335 | Stream? stream = await client.GetStreamAsync($"_framework/_bin/{reference.Location}"); 336 | references.Add(MetadataReference.CreateFromStream(stream)); 337 | 338 | } 339 | 340 | return references; 341 | } 342 | 343 | private async Task UpdateReferences(string baseUri) 344 | { 345 | Assembly[]? refs = AppDomain.CurrentDomain.GetAssemblies(); 346 | var client = new Lazy(() => new HttpClient 347 | { 348 | BaseAddress = new Uri(baseUri) 349 | }); 350 | 351 | foreach (Assembly? reference in refs.Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location))) 352 | { 353 | if (!s_references.ContainsKey(reference.Location)) 354 | { 355 | Stream? stream = await client.Value.GetStreamAsync($"_framework/_bin/{reference.Location}"); 356 | s_references.Add(reference.Location, MetadataReference.CreateFromStream(stream)); 357 | } 358 | 359 | } 360 | } 361 | } 362 | } 363 | -------------------------------------------------------------------------------- /wwwroot/css/open-iconic/font/fonts/open-iconic.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | Created by FontForge 20120731 at Tue Jul 1 20:39:22 2014 9 | By P.J. Onori 10 | Created by P.J. Onori with FontForge 2.0 (http://fontforge.sf.net) 11 | 12 | 13 | 14 | 27 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 45 | 47 | 49 | 51 | 53 | 55 | 57 | 59 | 61 | 63 | 65 | 67 | 69 | 71 | 74 | 76 | 79 | 81 | 84 | 86 | 88 | 91 | 93 | 95 | 98 | 100 | 102 | 104 | 106 | 109 | 112 | 115 | 117 | 121 | 123 | 125 | 127 | 130 | 132 | 134 | 136 | 138 | 141 | 143 | 145 | 147 | 149 | 151 | 153 | 155 | 157 | 159 | 162 | 165 | 167 | 169 | 172 | 174 | 177 | 179 | 181 | 183 | 185 | 189 | 191 | 194 | 196 | 198 | 200 | 202 | 205 | 207 | 209 | 211 | 213 | 215 | 218 | 220 | 222 | 224 | 226 | 228 | 230 | 232 | 234 | 236 | 238 | 241 | 243 | 245 | 247 | 249 | 251 | 253 | 256 | 259 | 261 | 263 | 265 | 267 | 269 | 272 | 274 | 276 | 280 | 282 | 285 | 287 | 289 | 292 | 295 | 298 | 300 | 302 | 304 | 306 | 309 | 312 | 314 | 316 | 318 | 320 | 322 | 324 | 326 | 330 | 334 | 338 | 340 | 343 | 345 | 347 | 349 | 351 | 353 | 355 | 358 | 360 | 363 | 365 | 367 | 369 | 371 | 373 | 375 | 377 | 379 | 381 | 383 | 386 | 388 | 390 | 392 | 394 | 396 | 399 | 401 | 404 | 406 | 408 | 410 | 412 | 414 | 416 | 419 | 421 | 423 | 425 | 428 | 431 | 435 | 438 | 440 | 442 | 444 | 446 | 448 | 451 | 453 | 455 | 457 | 460 | 462 | 464 | 466 | 468 | 471 | 473 | 477 | 479 | 481 | 483 | 486 | 488 | 490 | 492 | 494 | 496 | 499 | 501 | 504 | 506 | 509 | 512 | 515 | 517 | 520 | 522 | 524 | 526 | 529 | 532 | 534 | 536 | 539 | 542 | 543 | 544 | --------------------------------------------------------------------------------