Simplest way to use NHibernate for the official "ASP.Net MVC 3 Getting Started"-Tutorial - nhibernate

Clarified Updated Question - Start
In the official MVC 3 Getting Started-tutorial it seems to me that all we have to do to get ORM working are two steps.
First adding the simple MovieDBContext-code as described at the end of part 4 ..
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
.. and second in the beginning of part 5, with a simple right-click on the Controllers folder we can auto-generate a MoviesController that implements CRUD()-functionality using Entity Framework by simply telling which Model to use.
Now when using the web-application we can already write and read from the database.
What would be the simplest (or a simple) way to get this done for our Movie-Model with NHibernate instead of using Entity Framework?
Clarified Updated Question - End
Original question (only for additional background-info):
I'm trying to create an ASP.Net MVC 3 application that uses NHibernate and Postgres.
Background Info
Development is done on Windows with Visual Web Developer Express, the production environment will be/should be Linux+Mono.
Steps that have worked so far:
An ASP.Net Dynamic Data Entities Web Application using Npgsql and Postgres as the DB.
Successfully run on Windows development machine.
(Following this tutorial)
An ASP.Net MVC 3 application without using a database/model yet:
Succesfully run on Windows development machine and deployed to Linux production environment using Mono and Nginx. (Only as a proof of concept for myself not as a web app used by the public.)
An ASP.Net MVC 3 application with a model using SQL Server Express as the DB.
Successfully run on my Windows development machine.
(Following the MVC 3 Getting Started-tutorial)
Question
So far I managed to get Postgres to work with a "Dynamic Data Entities Web Application" but with an MVC 3 Web app I'm stuck on where/how to start. For the last mentioned MVC-3-Movie-Webapp I want to switch the DB from SQL Server Express to Postgres using NHibernate and Npgsql (NHibernate since Mono doesn't support Entity Framework).
When you look at the end of part 4 there's the simple MovieDBContext-code
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
and in the beginning of part 5, we autogenerate CRUD-stuff using Entity Framework by simply telling which Model to use.
(MoviesController.cs, Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml)
So I have that working with Entity Framework and SQL Server Express, but how would I achieve the same result by using NHibernate? (doesn't have to be with postgres immediately, sticking with SQL-Server as a first step would be fine) (Hopefully with similar simplicity, but getting the result itself would be great)
I found a lot of old stuff and how I would manually map things, but what would be a good-up to date standard way of achieving this with NHibernate for MVC 3?
(The closest thing I found was the source code mentioned in this thread, but it's 64 MB unzipped I got several "Projects not loaded successfully"-errors and the author said he uses MVC 2 so I think it's a little over my head for being a complete NHibernate noob.)
I think showing how this is done could be very useful for others as well, since the original tutorial is very easy to follow and is linked as the official starting point for MVC 3 app-development on http://www.asp.net/mvc ("Your First ASP.NET MVC App").
So I think this would be a great up to date example about how to use NHibernate with MVC 3.

Actually, those automated things haven't helpful enough in real world applications. We have to separate concerns and by using DataContext in UI Layer is not a good practice because that dependency will cause problems like lack of test-ability, violation of best practices. I think you need to have following things of your project
Separation of Concern (Layered Architecture - UI Layer, Servie Layer, Domain Layer, Infrastructure Layer)
Generic Repository and Unit of Work wrapping (Database functionalities, ORM - EF, NHibernate, etc
In your Service Layer process repositories and unit of work processings and expose Data Transfer objects or your domain objects (POCOs) to UI Layer
Use IOC to inject dependencies will help you to minimize dependencies
Create Unit test and Integration tests
Use Continuous Integration and Source control prefer (Distributed: Mercurial)
Useful References:
(Sharp Architecture) http://sharparchitecture.codeplex.com/
(IOC Container) http://www.castleproject.org/container/
(Generic repository) http://code.google.com/p/genericrepository/

NuGet is your friend. Here's a good example of using NuGet to automatically wire in your dependencies and configuration pretty much automatically.
Hope this helps.

Suggestion, don't get hung up on all the automatic stuff that the tutorials are showing you. Microsoft is just trying to show that you can easily get things started if you don't try to do anything unique.
Now for your situation. When you're making a controller, you're wanting to bind that controller with a type of model that you created somewhere. With nHibernate I'm thinking that you'll have manually created these POCO's and that you're using one of the many ways to map those POCO's through nHibernate to your database.
You won't be able to use the Entity Framework options because they're depending upon the features of the framework to provide information on the object, database, etc. Easiest things is to just make a controller that either gives you the options for CRUD or use an empty controller to build up your own ActionResults.
Hope this helps some and good luck with your project.

Related

How and where do I implement my recurring Hangfire job in the solution structure? Any sample apps?

I have recently started a working on my first project using the ABP Framework
I am implementing it as a module with no UI.
I would like to use Hangfire for recurring tasks, having advantage of the Hangfire UI/Dashboard that comes with it.
There is currently no documentation on Hangfire integration. The documentation page is empty. I understand ABP is relatively new, but I imagine someone has implemented it correctly.
The best I could find so far are Github issues(some of them still open) where users are trying to do the same.
Configuring Hangfire as Background Job Manager #2166
Use Volo.Abp.Hangfire Module ERROR #1313
I also noticed that there are two ABP Nuget packages for Hangfire:
Volo.Abp.HangFire
Volo.Abp.BackgroundJobs.HangFire
So my two main questions are:
By ABP convention, is it correct to implement the Hangfire job in my Name.Space.Domain project?
How do implement it as a recurring job?
In the mean time, I will patch up what I have drawn from the links I have shared and will happily share my solution if it works.
For the first question, it is totally fine to implement the business logic in the domain layer. Hence the Hangfire could handle some business logic.
For the second question, you can add this code in Configure function in start up:
app.UseHangfireDashboard();
app.UseHangfireServer();
RecurringJob.AddOrUpdate<yourjobsclass>(x => x.yourJobFunction, Cron.MinuteInterval(5));
Below are some resources that I think could help:
ASP.NET Core Applications: https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html
ASP.NET Applications: https://docs.hangfire.io/en/latest/getting-started/aspnet-applications.html

Steps to use Entity Framework in WCF

I have a question using Entity Framework in WCF. I am using .NET 4.5 with EF DbContext.
Here are the things I know to do to use EF in WCF. May be they are insufficient or some are not required.
Create EF ADO.NET Model.
Seperate the POCO classes to a seperate project (ProjectName: Entities) by using DbContext template generator.
Point the TT template of the POCO project to the edmx file in the data project (ProjectName: Data). "..\Data\MyEdmx.edmx"
Add [DataContract(IsReference(True))] and [DataMemeber] attributes in the .TT file of the POCO project so that the classes and properties will have the serialization attributes. Add Runtime.Serialization reference to the project and add the namespace to .TT file. This enables not to lose your attribute declaration while recreating the classes on a save of the .TT file or adding new entities.
Add ProjectName: Entities reference to Data project.
Turn off ProxyCreation and LazyLoading in the Context.tt file in the data project.
Add (ProjectName: Entities) and (ProjectName: Data) to your wcf service project.
Copy the EntityFramework connection string to your WCF project.
All your select methods in the service, must use .Include if you want the navigation objects to be populated. This gives better control when you want to load or or when you want limit data to show. Also, you don't get the child/related automatically due to lazyloading turned off.
Insert or Update or Delete, the service has to create the context and manually set the object state to be modified or added? Otherwise the changes will not be saved. Use the DbContext.Attach to attach and set the state of the entity appropriately Added,Modified, etc.
The problem I had was I could not find a good example of the steps to perform to use EF with WCF. I was able to see only bits and pieces. May be I am a late entrant to the WCF EF world hence could not find.
Not sure if I can use proxies WCF. I haven't understood completely the advantage of proxies yet.
I also read recommendations to use DTO as a layer between EF and the service. This requires a mapper to be in place. I don't know if I need it right away. But the idea is clear that it helps hide any unnecessary database columns showing in the business object. For example, audit columns such as created by, updated by etc we dont to show in the client.
I did not choose to use DataServices as I lose other binding options that I get from WCF. I don't know if it is a good thing to lose the simplicity of DataServices thinking about the future requirements of clients that require/support other binding mechanisms.
Any recommendations is appreciated.
Additional Update
I did find this in MSDN http://msdn.microsoft.com/en-us/library/ee705457(v=vs.100).aspx. Some of the links were pointing to pre-release documentation. But this gives some more ideas for me in using EF and WCF.
This articles shows how to use proxies with WCF, change tracking of POCO. This is a good start for me. If any one has more advise please provide your thoughts.
Update 2
*Another Excellent Link for N-Tier*
http://msdn.microsoft.com/en-us/magazine/dd882522.aspx
I am glad that the time I am spending is really educating me!
I progressed on using EF with WCF after lot of reading here and in other forums.
I followed the steps ahead. I was able to see the advantage of using DTO. This really allows you to hide fields that you don't need to expose to the client or other services. But I am holding back on introducing DTO due to time constraints.
I used context.Attach, context.Add and context.Entry.
I also did a small prototype to use WCF Data Service. That was very fast paced development. I am holding back on using WCF data services for now due to time constraint in learning its features.

EF4 Self-Tracking entities and WCF serialization creates stack overflow

I try to get above configuration working, but with no luck.
Step 1)
I started a new solution with a WCF Service Application project.
Step 2)
In this project, I added an edmx file and create a very simple model:
Entity Parent with Id and DisplayName
Entity Child with Id and ChildDisplayName
Association from Parent to Child, 1-to-m, resulting in NavigationProperties on both entities.
I generatedthe database without any problems. After generation, I inserted one Parent object with two related Child objects manually to the database.
Step 3)
I added the code generation, using the ADO.NET Self-Tracking Entity Generator.
I know that this should be done in diffrent assemblies, but to make it straight and easy, I put it all to the same project (the WCF project)
Step 4)
I just changed the IService Interface to create a simple get
[OperationContract]
Parent GetRootData(Int32 Id);
In the corresponding implementation, I take an Page object from the context and return it:
using (PpjSteContainer _context = new PpjSteContainer() )
{
return _context.ParentSet.Include("Child").Single(x => x.Id == Id);
}
Problem:
If I now run this project (the Service1.svc is start page), VS2010 automatically generates the test client to invoke the service. But once I invoke the service, I get an StackOverflowException! Debugging on the server side looks ok until it returns the object graph.
If I remove the Include("Child") everything is ok, but of course the Child objects are missing now.
I have no idea what I'm missing. I read a lot of howto's and guides, but all do it the way I did it (at least that's what I think)...
I tried the School example here, but this does not work for me as it seems the database generation and the coding in the example does not match.
So, I would much appreciate if someone could guide me how to make this work.
P.S.
Yes, all Entity-Classes are marked "[DataContract(IsReference = true)]"
Lazy-Loading is set to "false" in the edmx file
Edit:
I changed the WCF to be hosted in a console app and no longer in IIS. Of course then I had to write my own little test client.
Funny enough, now everything's working.
I of course have no idea why, but at least for my testing this is a solution...
Have a look here. Basically you have to make the serializer aware of cycles in the navigation properties.

OData WCF Data Service with NHibernate and corporate business logic

Let me first apologise for the length of the entire topic. It will be fairly long, but I wish to be sure that the message comes over clearly without errors.
Here at the company, we have an existing ASP.NET WebApplication. Written in C# ASP.NET on the .NET Framework 3.5 SP1. Some time ago an initial API was developed for this web application using WCF and SOAP to allow external parties to communicate with the application without relying on the browsers.
This API survived for some time, but eventually the request came to create a new API that was RESTfull and relying on new technologies. I was given this assignment, and I created the initial API using the Microsoft MVC 2 Framework, running inside our ASP.NET WebApplication. This took initially quiet some time to get it properly running, but at the moment we're able to make REST calls on the application to receive XML detailing our resources.
I've attended a Microsoft WebCamp, and I was immediatly sold by the OData concept. It was very similar then what we are doing, but this was a protocol supported by more players instead of our own implementation. Currently I'm working on a PoC (Proof of Concept) to recreate the API that I developed using the OData protocol and the WCF DataService technology.
After searching the Internet for getting NHibernate 2 to work with the Data Services, I succeeded in creating a ReadOnly version of the API that allows us to read out the entities from the internal business layer by mapping the incoming query requests to our Business layer.
However, we wish to have a functional API that also allows the creation of entities using the OData protocol. So now i'm a bit stuck on how to proceed. I've been reading the following article : http://weblogs.asp.net/cibrax/default.aspx?PageIndex=3
The above articly nicely explains on how to map a custom DataService to the NHibernate layer. I've used this as a base to continue on, but I have the "problem" that I don't want to map my requests directly to the database using NHibernate, but I wish to map them to our Business layer (a seperate DLL) that performs a large batch of checks, constraints and updates based upon accessrights, privledges and triggers.
So what I want to ask, I for example create my own NhibernateContext class as in the above articly, but instead rely on our Business Layer instead of NHibernate sessions, could it work? I'd probably have to rely on reflection alot to figure out the type of object I'm working with at runtime and call the correct business classes to perform the updates and deletes.
To demonstrate with a smal ascii picture:
*-----------------*
* Database *
*-----------------*
*------------------------*
* DAL(Data Access Layer) *
*------------------------*
*------------------------*
* BUL (Bussiness Layer) *
*------------------------*
*---------------* *-------------------*
* My OData stuff* * Internal API *
*---------------* *-------------------*
*------------------*
* Web Application *
*------------------*
So, would this work, or would the performance make it useless?
Or am I just missing the ball here?
The idea is that I wish to reuse whatever logic is stored in the BUL & DAL layer from the OData WCF DataService.
I was thinking about creating new classes that inherit from the EntityModel classes in the Data.Services namespace and create a new DataService object that marks all calls to the BUL & DAL & API layers. I'm however not sure where/who to intercept the requests for creating and deleting resources.
I hope it's a bit clear what I'm trying to explain, and I hope someone can help me on this.
The devil is in the details, but it sounds like the design you're proposing should work.
The DataService class is where you get to define the access rights applicable to everyone, configuration settings, and custom operations. In this scenario, I think you will be focusing more on the data context instead (the 'T' in DataService).
For the context, there are really two interesing paths: reads and writes. Reads happen through the IQueryable entry points. Writing a LINQ provider is a good chunk of work, but NHibernate already supports this, although it would return what I imagine we're calling DAL entities. You can use query interceptors to do access checks here if you can express those in terms that the database would understand.
The update path is from what I understand where you are trying to run more business logic (you mentioned validation, extra updates, etc). To do this, you'll want to focus on the IUpdatable implementation (IDataServiceUpdateProvider if you're using the latest version). Here you can use whichever objects you want - they could be DAL objects or business objects. You can do everything in the DAL and then run validation on SaveChanges(), or do everything on business objects if they validate as they go.
There are two places where you might 'jump' from one kind of objects to another. One is in the GetResource() API, where you get an IQueryable, presumably in term of DAL entities. The other is in ResolveResource(), where the runtime is asking for an object to serialize, just like it would get from an IQueryable, so it's presumably also a DAL entity.
Hope this helps - doing uniform access over non-uniform APIs can be hard, but often well worth it!

Session Per ViewModel in Desktop Application with Repository

I have been writing a WPF DESKTOP application using NHibernate, WPF, Prism and Unity Container but have a problem in terms of Session Management in Services / Repositories and how to do it cleanly through dependency injection using Unity.
Having read Building A Desktop To Do-Application With NHibernate I now have a Session Per ViewModel / Presenter.
However, if I have several services on my viewmodel I have to pass the Session into each and every service which seems cumbersome and not quite right as I want to perform all data access through a repository.
e.g
CustomerMaintenanceViewModel
{
service1.Session = SessionForThisPresenter;
service2.Session = SessionForThisPresenter;
service3.Session = SessionForThisPresenter;
service1.GetAllSomething();
service2.GetAllSomething();
service3.GetAllSomething();
}
Each service is essentially a facade over a repository and I would want each repository for this presenter to be involved in the same session without explicitly setting it.
Any advice on how to handle this would be most appreciated as I am sure there is a solution quite close but I am not sure how to do it.
I suggest you look into uNhAddIns.
It has a full WPF example using MVVM.