Git Product home page Git Product logo

contosouniversitycore's People

Contributors

davidroth avatar jbogard avatar kripergvg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

contosouniversitycore's Issues

Add Docker support

I would love to see "the Dockerfile" for this :)

I read Microsoft discourages Docker for ASP.NET Core with Full .NET Framework, I think that's also the reason you can't right-click "Add > Docker support" in Visual Studio on a aspnet core with full net framework project.
But I started a project during the time when aspnet core was available, but the net core framework was still not/barely released, and I would love to deploy it in Docker anyway.

They do describe how to approach it, but without a working example I haven't been able to get this working yet.

So guidance on how to set this up via this project would be awesome.

Course edit database constraint error

Jimmy,

First off I love your work, really interesting. I have a question and a issue.

The questions - where to you generally put core business validation logic. I am talking about a situation where the model state is valid, but the pending change violates some high-level business rule. (ex an instructor can only be assigned to two classes at a time).

The issue I found is an error if you modify a course and remove the selected department (set the drop down to nothing). When you save course, it passes model validation but it throws and error/ violates a database constraint given the null department . The end result in the sample application is the user is stuck on the course edit page with no error feedback. I know the simple answer would be to validate the model to make sure it has a valid department. What I wanted was some type of centralized valuation. I am assuming that I could add an additional filter and return json errors if appropriate?

Let me know your thoughts

Mapper.AssertConfigurationIsValid throws Mapper not initialized

Hi. I tried calling Mapper.AssertConfigurationIsValid on my project but it threw an exception. Aside from services.AddAutoMapper(typeof(Startup)) and a MappingProfile, what else am I missing? Thanks!

Mapper.AssertConfigurationIsValid();

Exception details

System.InvalidOperationException
  HResult=0x80131509
  Message=Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.
  Source=AutoMapper
  StackTrace:
   at AutoMapper.Mapper.get_Configuration()
   at AutoMapper.Mapper.AssertConfigurationIsValid()
   at Gldd.Api.Startup.ConfigureServices(IServiceCollection services) in C:\git\cutter-stripcharts-prototype\src\Gldd.Api\Startup.cs:line 36
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
   at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder.<>c__DisplayClass12_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Gldd.Api.Program.Main(String[] args) in C:\git\cutter-stripcharts-prototype\src\Gldd.Api\Program.cs:line 10

Question: Why not use EF migrations?

Hi Jimmy,

I was reading through the code in this repo and started wondering why you do not use EF migrations. Can you elaborate on that decision?

Are there any pitfalls that makes it preferable just to have a hand-crafted SchemaAndData.sql?

Best, Egil

EF6 with core

Hi Mr. Bogard,

Invaluable example for using mediatr and automapper. In the docs at microsoft, they say make your EF6 code to be in a project, but I don't see anything like that in this example.

Build.ps1 tools

What is rh.exe and Octo.exe? free tools ?

dotnet command:

exec { & dotnet restore }
exec { & dotnet build -c Release --version-suffix=$buildSuffix }

Documentation

Hi Jimmy, I know I am asking too much, but is there a documentation for this project architecture? You did an amazing job by organizing the items by feature and I want to use this architecture on my project. Thank you very much Sir.

Unable to load DLL 'libuv': The specified module could not be found.

I just cloned this solution, created the SQL Server database, tried running it two different ways,

  1. by clicking the IIS Express button in VS
  2. at the command line, entering "dotnet run"

I get the same error. I investigated on StackOverflow and there was some mention of adding a new element to the .csproj file, like so:

<PropertyGroup>
    <RuntimeIdentifier>win7-x86</RuntimeIdentifier>
    <BaseNuGetRuntimeIdentifier>win7-x86</BaseNuGetRuntimeIdentifier>
</PropertyGroup>

This is the original section:

<PropertyGroup>
  <TargetFramework>net461</TargetFramework>
  <PreserveCompilationContext>true</PreserveCompilationContext>
  <AssemblyName>ContosoUniversityCore</AssemblyName>
  <OutputType>Exe</OutputType>
  <PackageId>ContosoUniversityCore</PackageId>
  <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>

... and this is the modified section...

<PropertyGroup>
  <TargetFramework>net461</TargetFramework>
  <PreserveCompilationContext>true</PreserveCompilationContext>
  <AssemblyName>ContosoUniversityCore</AssemblyName>
  <OutputType>Exe</OutputType>
  <PackageId>ContosoUniversityCore</PackageId>
  <PlatformTarget>AnyCPU</PlatformTarget>
  <RuntimeIdentifier>win7-x86</RuntimeIdentifier>
  <BaseNuGetRuntimeIdentifier>win7-x86</BaseNuGetRuntimeIdentifier>
</PropertyGroup>

It still produces an exception, but this time it's a BadImageFormatting exception.

Any ideas how to get this to run?

Question: how would you transform this into a multi-project solution?

First of all, great sample to illustrate CQRS! I hope you are allowing questions and I hope this is a good place to put them.

In a larger-scale application, you would probably make multiple projects. Starting with something like:

  • Website
  • Logic
  • Data
  • Domain

How would you refactor this sample into multiple projects?

Especially, where would you place the requests, request handlers, validators and models since all of them seems to be tightly coupled (also with the domain classes).

If we look at the Instructor feature. Both the Instructor domain object and the CreateEdit.CommandHandler use the CreateEdit.Command. Does this make the command part of the domain? Or do we create another project where commands and models go to?

Course Delete.Query & Delete.Command

Quick question on why you would have a query for delete and also why the delete command takes in so many parameters? I haven't seen the original Contoso source so is this an artifact of that or is this a personal choice?

Validation not tested.

There are tests for each of the commands, but none of them end up exercising the validation on the commands. That is the FluentValidation or the ComponentModel.DataAnnotation attributes that are on some command properties.

For example, if the following test was added to the ContosoUniversityCore.IntegrationTests.Features.Department.CreateTest class:

[Fact]
public async Task Should_not_create_invalid_department()
{
    var command = new Create.Command
    {
        Budget = 10m,
        Name = "Engineering",
        StartDate = DateTime.Now.Date,
        Administrator = null,
    };

    // really this should fail somehow...
    await SendAsync(command);

    var created = await ExecuteDbContextAsync(db => db.Departments.Where(d => d.Name == command.Name).SingleOrDefaultAsync());

    created.ShouldBeNull();
}

The test would fail because the command's validator rules are not exercised. Specifically this one:

        public class Validator : AbstractValidator<Command>
        {
            public Validator()
            {
                //...
                RuleFor(m => m.Administrator).NotNull();
            }
        }

It seems they are only evaluated on model binding, but no tests exercise that path as it would require spinning up an in-memory ASP.Net server.

How do you normally test the validations? It seems that command validation testing is a central part of the tests that should be in place.

System.MissingMethodException: Method not found

Project compiled and home page loads fine. But when I click either Student, Contacts, Courses and Instructor tabs, I get following error

System.MissingMethodException: Method not found: 'Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.ModelBindingMessageProvider Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.BindingMetadata.get_ModelBindingMessageProvider()'.

I tried upgrading AspCore.MVC to 2.2.0, but still doesn't help.
Also, tried clearing nuget cache and rebuilding doesn't help

**Note: Only Department tab works
image

How do you specify the View file locations for the Feature folders?

I really like the "features" organization structure you use -- it fixes the annoying folder structure convention used by .Net MVC. However, when I try to duplicate the structure I of course get a "The view 'Index' was not found. The following locations were searched... (the usual paths)" exception.

How do you overcome specify the new View locations? I searched the ContosoUniversityCore project file-by-file but I don't see where you declare the new location for views. What am I missing?

Thank you! I've been self-updating my programming skills from 1998-era PHP to modern CQRS+DDD and you, Udi Dahan and select others have made the journey easy and enjoyable. Your blog and examples literally change lives.

SQL Server deadlocks when using DbContextTransactionFilter?

We used the DbContextTransactionFilter in one of our projects (ASP.Net Core 1, EF6, full .Net framework) to ensure that each request was wrapped up in a SQL Server transaction. We had to remove it because SQL Server was killing queries due to deadlocks and causing the app to crash, once the number of users ramped up. (We're talking handfuls of concurrent users, not hundreds.) Is this something anyone has come across before, and is there another way to deal with it other than turning off the per-request transaction?

Migrations fail

When I cloned this repo and attempted to enable migrations / add migrations I get

Enable-Migrations -verbose
Using StartUp project 'ContosoUniversityCore'.
Using NuGet project 'ContosoUniversityCore'.
Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=15.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."
At C:\Users\piriej.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:718 char:5

  • $domain.SetData('project', $project)
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=15.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."
At C:\Users\piriej.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:719 char:5

  • $domain.SetData('contextProject', $contextProject)
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=15.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."
At C:\Users\piriej.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:720 char:5

  • $domain.SetData('startUpProject', $startUpProject)
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : SerializationException

System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetPropertyValue[T](Project project, String propertyName)
at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)
at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.
PM>

as per issue:
dotnet/ef6#231

Anyone else experiencing this? Current workarounds seem to involve changing the project structure back to the old csproj structure. Any thoughts?

@jbogard - Ran out of time to ask you at NDC Sydney, sorry mate.

Thanks in advance

Handling server side validation in the UI?

Firstly a great sample to learn about mediatr

I was wondering how would you handle the validation on the server with javascript disabled?

When I ran the sample I noticed that it returns a json validation response for RuleFor(), so in the UI how would you handle that so you can display a nice message to the user?

I noticed that the Create Post method wasn't even called

DbContext transaction mechanism possibly swallowing exception?

Hi Jimmy,

Looking at this code, I can't help but think it could swallow an exception. That catch statement calls RollbackTransaction, but doesn't throw.

Since the associated MVC filter rolls back if an exception is caught and rethrows, shouldn't CommitTransactionAsync just take care of committing the transaction and disposing of it if all works well, and let the MVC filter handle the exception scenario? Or at least rethrow the exception (that's what the non-Core version does.

Cheers

Routing

How can I tell the controller to look in the Features folder and not to view/page folders when showing a certain page? Which part of the code?

Thank you very much

Putting AutoMapper profile into a class with a handler

As we use a specific Command/Query class for each handler, AutoMapper configurations are not reused by multiple handlers. And if AutoMapper configuration is specific to a handler, why don't we store it in the same file (like, Command, Profile, Handler)?

I feel a little uncomfortable about the indirect nature of AutoMapper as when I look at the handler's code and I'm not sure what's going on. Are there any complex mappings? Anything significant besides dumb mappings? I feel like moving the mapping configuration into the file with handler and command/query would make it a little bit more clear.

Why do we store all the mappings for a feature together? Do they share any common logic? Doesn't seem to be the case. In a way, I feel like grouping all the mappings together is a violation of the idea of grouping things by feature/function/etc. instead of grouping by type (i. e. all the mappings go together).

I'm debating myself about it in my current project, was curious what you Jimmy think about it.

Question: Why is the domain in a different folder / namespace?

Shouldn't be the domain model / entities / whateveryoucallthem be distributed among the feature modules / slices / whateveryoucallthem?

For example: ContosoUniversityCore.Domain.Course

shouldn't be located in

ContosoUniversityCore.Features.Courses.Course

/*
I've modified the Feature.Course namespace to Feature.Courses in plural. Maybe that's the reason you wouldn't do this? In our company we learned to "pluralize" modules / namespaces to avoid conflict with domain objects.
*/

Anyway, if my suggestion is wrong, could you provide a reasoning for having the Domain in a different folder / namespace / (module?)

Question: Why is the project targetting 4.6.1

I tried to build this project from scratch starting with a .Net Core 2.0 project type. I keep getting System.TypeInitializationException: 'The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.' FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
...in the schoolcontext on start.

When I compared my own project with this one, I see that this project is targeting .Net 4.6.1.
Can you explain why this targetting 4.6.1 and not .Net Core?

Instructor.OfficeAssignment and Instructor.HireDate have private setters, causing build errors

The two properties are declared in Instructor.cs as follows:

public DateTime HireDate { get; private set; }
public virtual OfficeAssignment OfficeAssignment { get; private set; }

When I try to build the project, I get these errors:

C:\{snip}\IndexTests.cs(37,17): error CS0200: Property or indexer 'Instructor.HireDate' cannot be assigned to -- it is read only
C:\{snip}\Delete.cs(75,17): error CS0272: The property or indexer 'Instructor.OfficeAssignment' cannot be used in this context because the set accessor is inaccessible

If I remove private from both setters, the solution builds fine. Is this the proper fix, or do those properties need to keep their setters as private? If the former, shall I submit a pull request?

Thanks,

Jon

Environment info:

  • Visual Studio 2015 Update 3
  • Windows 10

DbContext SaveChangesAsync not committing right away

When I call .SaveChangesAsync() on my EF Core context, should it be inserting into the database right away?

Or... is this a problem with the DbContext filter set up?

Here's how my code looks in a Features.Videos.Upload class...

Video video = new Vidoe();
video.Id = Guid.NewGuid();

// some more processing and more mapping of properties

await _db.Videos.AddAsync(video);
await _db.SaveChangesAsync();

Following the code, after the SaveChangesAsync() call, the logging shows the INSERT SQL statement. But there is no data in the database.

The data doesn't appear in the database until it goes through the Transaction Filter and hits the _currentTransaction?.Commit() method call in the CommitTransactionAsync() method.

The reason why this is a problem (I think).. is because I'm trying to save the video first, so I can then process some tags associated with it. When this code is called:

_db.TagVideos.AddAsync(new TagVideo { TagId = tagId, VideoId = videoId });

It too is generating an INSERT statement in the logger but then I'm getting an exception for a forein key constraint because the Video doesn't exist yet in the database.

Is this a problem with the Filter set up, EF Core, my Code...?

Thanks for any insight!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.