craftsman

A .NET scaffolding tool to help you stop worrying about boilerplate and focus on your business logic ๐Ÿš€

MIT License

Stars
1.1K

Bot releases are visible (Hide)

craftsman - v0.13.0-pre2

Published by pdevito3 almost 3 years ago

fixed an issue with the seeder for private entities

craftsman - v0.13.0-pre1

Published by pdevito3 almost 3 years ago

This is a prerelease that drives for more ddd based entities. entities now have private setters, factory methods, and updated tests and seeders.

craftsman - v0.12.2

Published by pdevito3 almost 3 years ago

Fixed

  • Fixed bulk add file and variable names
craftsman - v0.12.1

Published by pdevito3 almost 3 years ago

Updated

  • Removed unused response class and endpoint reference
  • Removed Consumes from Get list
craftsman - v0.12.0

Published by pdevito3 almost 3 years ago

Release Notes

Lots and lots of updates to this release with things I've been wanting to add and more lessons learned as I continue to dogfood things.

Some of the major items in here:

  • .NET 6 scaffolding. Everything is now scaffolded using .NET 6, implicit usings, shortened namespacing, and more. I didn't consolidate Startup and Program yet, but may in v0.13.
  • In memory Authorization Server scaffolding. This is a step towards a what I hope will be a ton of time savings. You can now scaffold out an in memory duende auth server along with your new projects. It is mostly based one the official duende template, with some slight differences. For exmaple, I didn't add consent pages in yet, but has some additional features like Tailwind CSS styling for the main pages. You can easily check out an exmaple with...
  • A new new:example command. I wanted to make it really easy to see examples for different types of scenarios, so I added a new command to easily get something together. Just runcraftsman new:example and follow the prompts!
  • All entities will now inherit from a BaseEntitiy that has a standardized Id Guid for your primary key and audit fields as well. These will be updated for you OOTB in db context now.

There's so much more as well. I think the project scaffolding is really moving in a good direction and is getting closer to a more stable position. Lots to add still, but it's at least starting to feel more mature.

As always, check out the docs for updates.

Also, I started a discord channel if you want to come join us! Feel free to reach out if you have any questions or issues.

๐Ÿš€ Additions and Updates

  • Added BaseEntity that all entities will inherit from.

    • Contains a Guid of Id marked as the primary key
    • Contains CreatedOn, CreatedBy, LastModifiedOn, and LastModifiedBy properties
  • Added a CurrentUserService to add a user to the CreatedBy and LastModifiedBy properties if a user is found. Built into db context

  • Added built in features to the add:feature command

  • New AddListByFk option for the add:feature command and Feature property of an entity.

  • New craftsman example or craftsman new:example command to create an example project with a prompted workflow to select. Basic, WithAuth, AuthServer, WithBus

  • Added .DS_Store and .env to gitignore

  • Added Consumer test

  • Added provider to test fixture when adding a bus

  • Added a mock IPublishEndpoint service to TestFixture when using MassTransit

    • update docs that mediatr handler tests aren't broken when pubilshing anymore
  • New policies added to swagger on add:entity scaffolding

  • New add:authserver command as well as an AuthServer option when creating a domain

    • No consent support (yet)
  • Added helper GetService method to TestFixture

  • Added Creation and Update Validators back to scaffolding. Easy enough to delete if you aren't using them

  • Added a NamingConvention property to the db template

    • options are:
      Class
      SnakeCase
      LowerCase
      CamelCase
      UpperCase
      
  • Updated to .NET 6

  • Updated nuget packages

    • Inlcudes a major release of Fluent Assertions that required updates to:
      • Functional test assertions (use HttpStatusCode.XXX)
      • Integration tests TestBase update for postgresto include 1.Seconds()
      • Integration test updates to await act.Should().ThrowAsync< where appropriate
  • Moved Policies to Feature

  • There is no more primary key property. A Guid with a name Id will be inherited by all entities.

  • Docker utilities for integration test refactored to use Fluent Docker wherever possible for better readability. Some enhancements were made as well (e.g. better container/volume naming, proper volume mounting).

  • Removed ErrorHandlerMiddleware and replaced it with ErrorHandlerFilterAttribute

    • Updated built in Exceptions
    • Updated thrown errors and associated tests in the features
  • Cleaned up test names

  • Modified CORS util to take in env

  • Added Secret back to Environment options

  • Added local config utilities for testing environments

  • Remove UseInMemoryDb app setting in favor of environment specific checks

  • Remove UseInMemoryBus app setting in favor of environment specific checks

  • Using statement shortening for reset function in test fixture

  • Consolidated multiple environments startups to one startup file

  • Update logging registration in Program.cs to no longer rely on appsettings

  • Updated FK support to better API

  • Moved env config from appsettings to environment variables

  • Production env no longer added by default

  • Features now include missing cancellation tokens as well as AsNoTracking properties

  • Removed automatic fluent validation to allow more control in domain operations. For example:

    var validator = new RecipeForCreationDtoValidator();
    validator.ValidateAndThrow(recipeForCreationDto);
    
    • this can be turned back on in WebApiServiceExtension by updating .AddFluentValidation(cfg => { cfg.AutomaticValidationEnabled = false; });

๐Ÿ› Pest Control

  • Removed the broken patch validation from command
  • No more 409 produced response annotation on POST
  • Descending sort tests now actually test desc instead of mirroring asc
  • Removed error handler comments in controller
  • Empty controller no longer added when no features present (fixes #40)
  • Messages project will be properly referenced when using a bus
  • Swagger policies won't get duplicates
craftsman - v0.11.1

Published by pdevito3 about 3 years ago

fix: removed extra ) from endpoint names

craftsman - v0.11.0

Published by pdevito3 about 3 years ago

Release Notes

This release has a lot of little cleanup items, as I've had the opportunity to dogfood this a bit and find a bunch of things that need fixing. I still plan on bringing in some of the big heavy hitting wins in v0.12.

Of note for this release was consolidating the 3 bounded context projects into one single project to promote simplicity and not prematurely optimizing. Additionally, there is a new add:feature command to quickly scaffold new features. More on this coming in v0.12.

As always, check out the docs for updates.

๐Ÿš€ Additions and Updates

  • Added an add:feature command (also works with new:feature)
  • Non-nullable guids will now have a default of Guid.NewGuid() unless otherwise specified
  • Added XML docs to release in csproj
  • Added a new features option to entities to allow for granular feature control. The accepted values are AdHoc, GetRecord, GetList, DeleteRecord, UpdateRecord, PatchRecord, AddRecord, and CreateRecord (same as AddRecord but available as an alias in case you can't remember!)
  • Instead of 3 BC projects (Core, Infra, Api) there will now be one. This helps with colocation and does force premature optimization for something like a model library and a heavily separated infra project.
    • Features dir changed to Domain with a features directory inside of it
    • Entities live on their respective entity folder in the domain with their feature
    • Removed the webapi suffix on the api project
    • Core directories moved to web api
    • Contexts dir changed to Databases
  • Removed save successful checks on add and update commands
  • Added better naming to PUT command variables
  • Guid PKs will no longer be added to the creation DTO
  • POST commands will no longer have a conflict check since you can't add a PK anymore
  • A conflict integration test will not be added anymore
  • NoKeyGenerated commands are no longer in dbcontext
  • Controller url all lowercase
  • Swagger comments on by default
  • 409 no longer shown on swagegr comments for POST
  • No more save successful check on delete command
  • Seeders have a sub DummyData directory
  • Sieve service registration moved to webapi service class
  • SolutionName to ProjectName

๐Ÿ› Pest Control

  • Seeder indentation in startup fixed
  • PUT commands will no longer throw 500 when entity is not modified (#31)
  • Route indentation fixed
  • Removed annoying comments from features
  • Fixed test name for basic gets in functional tests
  • Seeders in startup will newline when there are multiple entities
  • Unicode now onlyenforced on windows (for better emoji support)
  • Fixed isRequired property
  • Command prop for Update command has proper casing

๐Ÿ—‘ Removed

Removed the add:property cli - command

craftsman - v0.10.0

Published by pdevito3 over 3 years ago

Huge release incoming! It includes a ton of stuff. Most notably:

  • Added a slew of event scaffolding capabilities and updated the docs with examples
  • Updated the CLI to use Spectre Console
  • Updated everything to be in one solution

๐Ÿš€ Additions and Updates

Additions

  • Added SpectreConsole for a better CLI experience
  • Added add:bus command
  • Added add:consumer and add:producer commands for direct, topic, and fanout messages
  • Added Bus, Producers, and Consumers props to BC template
  • Added Messages to the domain template
  • Added add:message command
  • Added conflict test for add command when using a guid
  • Added tests for command and query exceptions
    • Didn't do them in the controller as that is not the dependency. Can test the exceptions causing the correct httpstatus code in the exception separately

Updates

  • Changed the new:domain output to a single solution with directories for each bounded context for easier management
  • Changed the seeder regions in StartupDevelopment.cs to comments
  • Changed the Logger settings in Program.cs
  • Updated add:entity and add:prop to now be called from the BC directory
  • Updated ProducesResponseType in controllers to generic Response type where applicable
  • Updated App Registrations to separate files
  • Updated Service Registrations to separate files
  • Updated entity name and entity prop names first letter to always be capitalized
  • Better namespacing for features in controllers using static classes for features
  • Updated functional test to pass without conflict
  • Updated nuget packages
  • Updated Program.cs to async
  • Changed migrations to happen after all bounded contexts are added

๐Ÿ—‘ Removed

  • Removed verbosity option from commands due to simplified spectre console
  • Removed legacy comment for include statement marker
  • Removed BC readme and updated sln readme

๐Ÿ› Pest Control

  • Fixed double error messages
  • Fixed incorrect help message for new:domain command (#24)
  • Fixed help text on list command
  • Fixed controllers to inherit from ControllerBase instead of Controller. fixes (#26)
  • Fixed extra space in the class in the dto classes when not abstract and trailing new line
  • If using a guid for a PK, it will be added to the creation dto (not manipulation or update) -- fixes #28
    • Guid PKs will have a default value of Guid.NewGuid() in their creation dto
  • PK already exists guard will be added for GUIDs and will be performed when adding a new entity and throw a 409 conflict via a new conflict exception if a record already exists with that guid. -- fixes #29
  • Fixed issue where POST would throw 500 when primary key != EntityNameId (e.g. PK of ReportId would break for an entity of ReportRequest) fixes #30
  • Fixed default value for strings on entities to use quotes
  • Fixed missing exception handling on add:bc command
craftsman - v0.9.3

Published by pdevito3 over 3 years ago

Release Notes

๐Ÿ› Pest Control

  • Removed autogen identity attribute and added explicit onmodelcreating callout for it (#23)
craftsman - v0.9.2

Published by pdevito3 over 3 years ago

Release Notes

๐Ÿ› Pest Control

  • Lingering DbContext/Db Name issue
craftsman - v0.9.1

Published by pdevito3 over 3 years ago

Release Notes

๐Ÿ› Pest Control

  • Db context will now be used instead of name in api scaffolding (#21)
  • Test utilities in functional tests will now be added when not using auth (#20)
craftsman - v0.9.0

Published by pdevito3 over 3 years ago

Release Notes

๐Ÿš€ Additions and Updates

  • Added a new vertical slice architecture
    • Projects have been consolidated and will now have a prefix of the solution name before each project type. For example, the api project with a solution name of ordering is ordering.webapi
  • Added a new:domain command to create a ddd based domain with various bounded contexts inside of it. this is recommended for long term maintainability
  • Added the add:bc command which will add a new bounded context to your ddd project
  • Testing completely rebuilt from the ground up. Now has unit, integration, and functional tests. Integration and Functional Tests can spin up their own docker db on their own to run against a real database.
  • Moved 'addGit' property from the api template to the domain template
  • Added a version or -v command to get the craftsman version
  • Added an initial db migration to run automatically on project creation
  • Added verbosity option to new domain and add bc
  • Added a version checker to make sure you are alerted if out of date
  • Added an add:prop alias
  • Added explicit add entity template with auth policies available to add
  • Added a production app settings by default
  • Changed the startup marker for dynamic services to a comment instead of a region
  • Readme will now be generated in the domain directory
  • Updated environment to have production as a reserved word instead of startup to be consistent with dotnet process
    • Will use startup and appsettings.production
    • Normal appsettings will be empty, but have all the config keys required to make migrations and builds possible
  • Updated the default Cors policy name
  • Consolidated launchsettings to have the same setup for all environments as it is just a setting for the IDE and not used for the release package
  • Removed micro command to consolidate and reduce complexity. if you still want to build a microservice, you can build a domain and deploy each bounded context as a microservice
    • Gateways were removed and may be added back with better integration in a future release
  • Removed the new:api command to focus on the DDD driven style
  • Removed ClientSecret to promote code+PKCE flow

๐Ÿ› Pest Control

  • Existing auth policies will now be skipped for registration when adding a new entity
  • Fixed documented response codes for delete, put, and patch from 201 > 204
  • Foreign keys will no longer be automatically included in features or DTOs for better performance (#2)

๐Ÿงน Housekeeping

  • Upgraded craftsman to net 5
craftsman - v0.8.2

Published by pdevito3 over 3 years ago

Release Notes

๐Ÿ› Pest Control

  • Fixed issue where xml comments would throw an error on non windows machines (#16)
craftsman - v0.8.1

Published by pdevito3 over 3 years ago

Release Notes

๐Ÿ› Pest Control

  • fixed bug when creating an api with auth settings
craftsman - v0.8.0

Published by pdevito3 over 3 years ago

Release Notes

๐Ÿš€ Additions and Updates

  • New add:micro command that scaffolds a new microservice template as well as an ocelot gateway
  • New port property on the new:api template to let you customize and api or microservice port on localhost
  • Added https default on local
  • Added additional startup middleware
    • UseHsts for non dev environments
    • UseHttpsRedirection with notes on even more secure options
  • New AuthorizationSettings object and authorization based properties on the environments for the new:api and new:micro commands
  • Added new GetEntity and DeleteEntity integration tests with and without auth
  • Added 401/403 response types to swagger comments when using auth
  • Added auth to swagger setup
    • note that secret is currently stored in appsettings
  • Auth added to integration tests when required

๐Ÿ› Pest Control

  • The CurrentStartIndex calculation in the PagedList class was broken and now has a new calculation.
  • Added null conditional operator (?.) to certain tests before .Data to make them fail more gracefully
    • Get{entity.Plural}_ReturnsSuccessCodeAndResourceWithAccurateFields()
    • Put{entity.Name}ReturnsBodyAndFieldsWereSuccessfullyUpdated
  • Cleaned up WebApplicationFactory to remove deprecated services.
  • Removed [Collection(""Sequential"")] from repo tests
craftsman - v0.7.0

Published by pdevito3 almost 4 years ago

Release Notes

๐Ÿš€ Additions and Updates

  • Removed the dependency on the foundation api template!

๐Ÿ› Pest Control

  • Fixed UseEnvironment in WebAppFactory to use Development
  • Fixed integration tests to use the new Response wrapper
  • Updated pagination tests to have proper keys due to default sort order possibly breaking these tests
craftsman - v0.6.1

Published by pdevito3 almost 4 years ago

Release Notes

๐Ÿ› Pest Control

  • XML comment info is now properly added to WebApi.csproj and the Swagger config
  • Extra line will no longer be added when no swagger contact url is provided
  • Repository now sets default sort order for proper sql compatibility in lists (issue #9)
craftsman - v0.6.0

Published by pdevito3 almost 4 years ago

Release Notes

This release requires an update of your foundation template to v0.4.0 You can upgrade by running this command: dotnet new Foundation.Api --update-apply

๐Ÿš€ Additions and Updates

  • Added table name and schema properties to entity
  • Added column name attribute to entity properties
  • Added Serilog by default in all new projects. This includes Console and Seq logging by default in Development. For non-Development environments, you'll need to add whatever logging you're interested in to their respective app-settings projects. There are just too many options to create a whole API on top of Serilog. for upgrade instructions see below.
  • Updated swagger implementation from nswag. for upgrade instructions see below.
  • Added Consumes and Produces headers to the controller endpoints
  • Added an option to manage additional swagger settings to your API endpoints. This will be turned off by default for now as dealing the with xml docs path is potentially burdensome, but will add a lot of valuable details for users consuming your API. If you are looking to add additional XML details, this is highly recommended.
  • Added a custom Response Wrapper to the GET and POST endpoints

๐Ÿ› Pest Control

  • Fixed launch settings to have null environment variable for Startup (Production). If you'd like to change this, be sure to update the appsetting lookup in Program.cs
  • Fixed POST endpoint that was lacking a [FromBody] marker
  • BasePaginationParameters will now have MaxPageSize and DefaultPageSize set as internal properties so they don't show up in swagger. These can be overridden in the distinct entity classes like so: internal override int MaxPageSize { get; } = 30;
  • Fixed controllers to be able to handle a name and plural with the same value (e.g. Buffalo)

Upgrade Walkthrough

NSwag Migration

  • Add the below packages to your webapi project and remove the Nswag package:

    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
    
    • In Webapi ServiceExtensions replace using NSwag with using Microsoft.OpenApi.Models; and update the swagger region to something like the below with the appropriate info for your project:

              #region Swagger Region - Do Not Delete
                  public static void AddSwaggerExtension(this IServiceCollection services)
                  {
                      services.AddSwaggerGen(config =>
                      {
                          config.SwaggerDoc(
                              "v1", 
                              new OpenApiInfo
                              {
                                  Version = "v1",
                                  Title = "",
                                  Description = "",
                                  Contact = new OpenApiContact
                                  {
                                      Name = "",
                                      Email = "",
                                      Url = new Uri(""),
                                  },
                              });
                      });
                  }
              #endregion
      
    • In Webapi AppExtensions, update the swagger region to the below:

              #region Swagger Region - Do Not Delete
              public static void UseSwaggerExtension(this IApplicationBuilder app)
              {
                  app.UseSwagger();
                  app.UseSwaggerUI(c =>
                  {
                      c.SwaggerEndpoint("/swagger/v1/swagger.json", "");
                  });
              }
              #endregion
      

Adding Serilog

  • If you have an existing project and want to add this to your project, you'll need do this manually :

    • Add the following packages to webapi:

    • Update your Program to the following:

    namespace WebApi
    {
        using Autofac.Extensions.DependencyInjection;
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.Extensions.Configuration;
        using Microsoft.Extensions.Hosting;
        using Serilog;
        using System;
        using System.IO;
        using System.Reflection;
    
        public class Program
        {
            public static void Main(string[] args)
            {
                var myEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                var appSettings = myEnv == null ? $"appsettings.json" : $"appsettings.{myEnv}.json";
    
                //Read Configuration from appSettings
                var config = new ConfigurationBuilder()
                    .AddJsonFile(appSettings)
                    .Build();
    
                //Initialize Logger
                Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(config)
                    .CreateLogger();
    
                try
                {
                    Log.Information("Starting application");
                    CreateHostBuilder(args)
                        .Build()
                        .Run();
                }
                catch (Exception e)
                {
                    Log.Error(e, "The application failed to start correctly");
                    throw;
                }
                finally
                {
                    Log.Information("Shutting down application");
                    Log.CloseAndFlush();
                }
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .UseSerilog()
                    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup(typeof(Startup).GetTypeInfo().Assembly.FullName)
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .UseKestrel();
                    });
        }
    }
    
    • Update your appsettings.Development to:
    {
      "AllowedHosts": "*",
      "UseInMemoryDatabase": true,
      "Serilog": {
        "Using": [],
        "MinimumLevel": {
          "Default": "Information",
          "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
          }
        },
        "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
        "WriteTo": [
          { "Name": "Console" },
          {
            "Name": "Seq",
            "Args": {
              "serverUrl": "http://localhost:5341"
            }
          }
        ]
      },
    }
    
craftsman - v0.5.0

Published by pdevito3 almost 4 years ago

Release Notes

๐Ÿš€ Additions and Updates

  • Added add:entities alias for the add:entity command
  • Can now add Guid or other non-integer primary key

๐Ÿ› Pest Control

  • Fixed bug where postgres library was getting added every time
craftsman - v0.4.2

Published by pdevito3 almost 4 years ago

Release Notes

๐Ÿ› Pest Control

  • Seeder was not getting added to StartupDevelopment when using add:entity command