I can't make swashbuckle.examples work with datamodel inheritance - swagger

I have taken over a project that uses https://github.com/mattfrear/Swashbuckle.Examples
I'm new to swagger.
It works fine, except when I have a model that is inherited from a baseclass, then it only shows a subset of the baseclass, ignoring the inherited model completely
This works:
[SwaggerRequestExample(typeof(WebAPIextModels.Models.BASEBooking), typeof(RequestValueBASEBook))]
public IHttpActionResult Book([FromBody] WebAPIextModels.Models.BASEBooking apiBooking)
This does not:
[SwaggerRequestExample(typeof(WebAPIextModels.Models.INHERITBooking), typeof(RequestValueINHERITBook))]
public IHttpActionResult Book([FromBody] WebAPIextModels.Models.INHERITBooking apiBooking)

Related

Database Not Being Created In Code First Approach

I have seen a few questions like this, but none seem to answer my question - the most common response seems to be 'Lazy Loading - The database/tables will be created when you try to access them' in this case I am:
Dim students As List(Of Student) = db.Students.ToList
The above is throwing an error, because students table is empty/null.
Here is my (very simple) SchoolContext:
Imports System.Data.Entity
Public Class SchoolContext
Inherits DbContext
Public Students As DbSet(Of Student)
End Class
Here is my SchoolInitialiser class:
Imports System.Data.Entity
Public Class SchoolInitializer
Inherits DropCreateDatabaseAlways(Of SchoolContext)
Protected Overrides Sub Seed(context As SchoolContext)
Dim students As List(Of Student) = New List(Of Student) From {
New Student("Jessica", "Jones"),
New Student("Chuck", "Norris"),
New Student("Rambo", "John")
}
For Each student In students
context.Students.Add(student)
Next
context.SaveChanges()
End Sub
End Class
And my connection string in web.config:
<add name="SchoolContext" connectionString="Data Source= (LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\school.mdf;Initial Catalog=aspnet-WebApplication1-20160205092922;Integrated Security=True" providerName="System.Data.SqlClient" />
And finally my global.asax where I am calling the SetInitialize function
Imports System.Data.Entity
Imports System.Web.Optimization
Public Class MvcApplication
Inherits System.Web.HttpApplication
Protected Sub Application_Start()
Database.SetInitializer(New SchoolInitializer)
AreaRegistration.RegisterAllAreas()
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
End Sub
End Class
No database seems to be created within my AppData folder and as far as I can tell, everything is set up okay? Any suggestions?
I am following the following tutorial: https://www.youtube.com/watch?v=VAtVv1Q7ufM
Thanks!
So I figured this one out, in case anybody comes across a similar problem. I was using VB, so I imagine some things got lost in translation from c#.
There were actually a few issues for this. The first one was that the StudentContext class needed properties for the tables, not global variables:
'NOT Public Students As DbSet(Of Student)
Public Property Students() As DbSet(Of Student)
After this, the errors were easier to figure out. The second error was due to not having a key on my Student model, so I added this:
<Key()>
Public Property _StudentID As Integer
To both the property and the global variable. Next, it was not connecting to the database for some reason, so I had to download and install localDB.
Finally, it was complaining that I didn't have a parameterless constructor. So I had to add in an empty constructor in my student model.
FINALLY - everything is working (yay)

Project Structure using MVC 4

As the subject says...this question is about setting up the correct structure for my project only. if you think there is a better place to ask this question then please advise.
I have a MVC 4 project using ET & repository pattern. I have DAL & UI layer at this point.
Currently i am using my DAL for data access and I created my Interfaces & ViewModels within my Data Access Layer. i have a feeling i am doing it wrong. here is my Sample Set up.
MY DAL LAYER (Which contains below Interface, Repo & ViewModel)
DAL.ViewModel
Public Class ProductSummaryViewModel
Property productGUID As Integer
Property productName As String
End Class
DAL.Interface (For Repostiory Pattern)
Public Interface IProductRepository
Property ProductIdentityID As Integer
Property ImageMainPath As String
End Interface
DAL.Products Repository
Public Class productsRepository
Implements IProductRepository
Private _db As websolutionsEntities = New websolutionsEntities()
Public Function AddProduct(ByVal prdSummary As ProductSummaryViewModel) As Boolean Implements IProductRepository.AddProduct
_db.AddProduct(prdSummary )
Return true
End Function
And here is my Controller
Private ProductRepoitory As DAL.IProductRepository
Sub New()
Me.new(New DAL.productsRepository())
End Sub
Sub New(ByVal repo As DAL.IProductRepository)
repo = ProductRepoitory
End Sub
Public Function AddItem(ByVal prd As DAL.ProductSummaryViewModel) As ActionResult
Dim test as boolean = DAL.ProductRepoitory.AddItem(prd)
End Function
My project will grow in near future, so I want to set it up properly, however I don't want to make it too complicated as well for others and myself. Please advise with your suggestions.
Your can divide your project like this:
CORE
Interfaces(Ex: IProductRepository)
Domain(Ex: Product)
DAL
ProductRepository
MVC
ViewModels or Models(Ex: ProductsSummaryViewModel)
Controllers(Ex: ProductsController)
Make folders like Interfaces, Domain under CORE. You probably already have a controller folder in MVC frontend project. You also probably already have a folder called Models, just use that for ViewModels. Any thing used just for display purposes like the ViewModel classes should just exist in the front end.

Nested Object Scaffold ASP.net MVC 3 VB.net

I am complete beginner with ASP.net and VB.net, I created two classes one for Teams and another for Fixtures which will take in 2 teams.
Imports System.Data.Entity
Public Class Team
Public Property ID() As Integer
Public Property Name() As String
Public Property Points() As Integer
End Class
Public Class TeamDBContext
Inherits DbContext
Public Property Teams() As DbSet(Of Team)
End Class
Imports System.Data.Entity
Public Class Fixture
Public Property ID() As Integer
Public Property Week() As Integer
Public Property HomeTeam() As Team
Public Property AwayTeam() As Team
End Class
Public Class FixtureDBContext
Inherits DbContext
Public Property Fixtures() As DbSet(Of Fixture)
End Class
I created a FixturesController with the read/write actions and views. However when I go to create a Fixture in my application I only see a field for Week and not field for HomeTeam or AwayTeam.
Well you need to add them manually. Brad Wilson wrote a nice article explaining in details how you could make the templated helpers to recursively descend in your nested models.
Also as a side remark you probably don't need 2 db contexts, one should be enough and it could contain both your Teams and Fixtures:
Public Class FixtureDBContext
Inherits DbContext
Public Property Teams() As DbSet(Of Team)
Public Property Fixtures() As DbSet(Of Fixture)
End Class

ASP.NET MVC UpdateModel - fields vs properties?

I refactored some common properties into a base class and immediately my model updates started failing. UpdateModel() and TryUpdateModel() did not seem to update inherited public properties.
I cannot find detailed info on MSDN nor Google as to the rules or semantics of these methods. The docs are terse (http://msdn.microsoft.com/en-us/library/dd470933.aspx), simply stating:
Updates the specified model instance using values from the controller's current value provider.
SOLVED: MVC.NET does indeed handle inherited properties just fine. This turned out to have nothing to do with inheritance. My base class was implemented with public fields, not properties. Switching them to formal properties (adding {get; set; }) was all I needed. This has bitten me before, I keep wanting to use simple, public fields. I would argue that fields and properties are syntactically identical, and could be argued to be semantically equivalent, for the user of the class.
MVC will bind to properties of the inherited class. The model binder calls something like typeof(yourtype).GetProperties() which returns all the inherited members just fine.
Just tested it out with:
public class PersonBase
{
public string Name { get; set; }
}
public class User : PersonBase
{
public string FavoriteFood { get; set; }
}
"My assumption is the methods are reflecting on the top class only,"
How would that work? The "top" class IS the base class too.
this one made me curious too.
i made a edit form for a class Manager who derives from a Person
(after all, managers are persons too :-))
then in this action method
public ActionResult Edit(Manager manager )
{
return View(manager);
}
which wass called from a view with the Manager (derived type) as strong typed Model variable, when hovering the manager variable, it shows me the base class (it actually said: base: Person ) AND the one extra property for the manager
tried the formcollection too, and that also works:
public ActionResult Edit(FormCollection formCollection )
{
Manager manager = new Manager();
UpdateModel(manager );
return View(manager);
}

ASP.NET MVC: Controller constructors

i'm just starting out with asp.net mvc. It's a long way before you can really get to a live project. At the moment i'm working to build a blog using the asp.net mvc unleashed book.
However, i don't understand the 2 constructors in the BlogController (see question below)
Thx...
FIRST
The BlogController has a private variable '_repository'
Private _repository As BlogRepositoryBase
Public MustInherit Class BlogRepositoryBase
'blog entry methods
Public MustOverride Function ListBlogEntries() As List(Of BlogEntry)
Public MustOverride Sub CreateBlogEntry(ByVal BlogEntryToCreate As BlogEntry)
Public MustOverride Function QueryBlogEntries() As IQueryable(Of BlogEntry)
End Class
The BlogRepositoryBase gets inherited by EntityFrameworkBlogRepository _
The EntityFrameworkBlogRepository connects with BlogDBEntities
NEXT
The controller has 2 constructors 'new' and 'new with a parameter'
Public Sub New()
Me.New(New EntityFrameworkBlogRepository())
End Sub
Public Sub New(ByVal repository As BlogRepositoryBase)
_repository = repository
End Sub
QUESTIONS
What's going on with the constructors, i don't get that
How can a class of type 'EntityFrameworkBlogRepository' be passed to 'sub new' as BlogRepositoryBase? Isn't that another type?
The default constructor is calling the constructor with a parameter with a new instance of a particular type of BlogRepositoryBase class. EntityFrameworkBlogRepository must derive from this base class. The reason that you specify the base class (I would have used an interface, but I digress) is so in your tests you can specify a different type of repository -- one, perhaps, that doesn't even connect to a database by instantiating it directly via the non-default constructor. The framework wiil always use the default constructor, thus you have to both provide it and provide a suitable implementation of the repository using it.
FWIW -- this is how I would do it (in C# -- my brain isn't working well enough to translate into VB, yet).
protected IBlogRepository Repository { get; set; }
public BlogController() : this( null ) {}
public BlogController( IBlogRepository repository )
{
this.Repository = repository ?? new EntityFrameworkBlogRepository();
...
}
Tested as
public void Test()
{
var repository = MockRepository.GenerateMock<IBlogRepository>();
var controller = new BlogController( repository );
...
repository.VerifyAllExpectations();
}
EntityFrameworkBlogRepository is derived from BlogRepositoryBase
The 'magic' in the constructors is called Dependency Injection. (Wiki has more on that here.) In short, it is a way of making your code more maintainable and testable by passing it it's dependencies ... if you change the repository type you need not rip out most of your code.
Kindness,
Dan
Coding custom IControllerFactory or DefaultControllerFactory inherits class. And SetControllerFactory global.asax.
Haaked becomes reference very much.
TDD and Dependency Injection with ASP.NET MVC

Resources