Database to full asp.net Mvc App – in 5 minutes

Database to full asp.net Mvc App – in 5 minutes

So you are sitting in one of those interminable tuesday morning meetings at work, trying not to spill your now-cold coffee, wondering if the cryptic doodling on your pad suggests anything about your state of mind, when the project manager says ‘..and I’m sure Nick could convert the database into a fully functional Asp.Net Mvc application, so that we can manage the data in a more user friendly and secure manner. How long do you think that would take, Nick?’.

And now everyone turns to look at you.

Scrambling to figure out what the context is and how the conversation has turned to this, you pluck a hopefully reasonable figure out of the air. ‘Yeah, should be able to turn that around in a couple of weeks..’ you say brightly.

‘Excellent’ says the project manager, ‘I knew i could depend on you’. Everyone smiles in relief, and the meeting then proceeds to plan the complex multi-team delivery of downstream modules, all of it dependent on your proposed timescale.

As you all file out of meeting room 7c, the project manager says ‘..oh by the way, i believe its an Oracle database that we need converting to the Mvc app, and we’ll be needing it to use WebApi, and Asp.Net Identity for secure authentication etc, that’s not going to be a problem is it?’

‘Um..’ you say.

Back at your desk, you are wondering if anyone has ever undertaken to build an asp.net mvc app on an Oracle database, doesn’t sound very likely. How on earth are you going to get off the ground with this, and deploy in 2 weeks?

Let me show you how to do it in 5 minutes.

[You will need Visual Studio (2012+) and the CodeTrigger For Visual Studio extension (Full Trial, or Professional Version, v4.8.6.5+), Windows 7.1+, .Net Framework 4.6.1+. Once you got that setup, make a note of the time and begin]

Step 1. Start a new CodeTrigger project within Visual Studio, give it a name, and select the ‘DB to Multi-tier Mvc ..’ wizard. Click next.

pp1b-pr1

Step 2. Select your data source type, and configure the connection settings. Click ‘Connect’ to verify the settings, and click ‘Create’.

pp2a-pr2

pp11a-pr11

 

Step 3. Voila, the multi-tier Visual Studio project is generated and pre-built. (If you don’t have nuget automatic package download enabled, you may have missing package build errors at this stage, in this case, enable nuget automatic package download on your solution, or otherwise download the missing asp.net core packages from nuget, and rebuild. If you do have nuget automatic package download enabled then this is all done for you).

Note that this wizard will attempt to automatically create the identity tables required by Asp.Net identity, in your database. If those tables already exist then they will not be regenerated.

In the ‘Schema Objects’ tab, select any tables you want to be represented in the final application. If you have 15 tables or less, you might as well click the ‘Select all’ checkbox.

pp3b-pr3

Step 4. Click on the ‘Business Objects’ tab. The business model is generated from your previous selections and all related business model entities are displayed for your selection, along with their relationships. Again, if the number of model entities is about 15 or less, you may as well select all, otherwise choose judiciously according to your project needs.

pp4b-pr4

Step 5. Shoot! Click the red button to generate the selected code classes. Stand back and be happy as CodeTrigger spews out several thousand lines of required code in a matter of seconds! At this point the project/solution will build itself and report happy. If there’s any outstanding tasks, they might be reported in the ‘Things to do’ tab but I find that useful only when I’ve changed some of the default automatic code generation settings (like automatic sql scripting or automatic project file update).

pp5a-pr5

Step 6. Hit F5 to build and run. At this point (or soon after) when I’m building an Oracle based MVC app (as opposed to Sql Server or MySQL), I sometimes find that the solution fails with an unhandled Oracle client Exception. This seems to be because Oracle is still in shock about what just happened. If this occurs I close Visual Studio and re-open it, and that seems to cure the issue once and for all.

Enjoy the sight of your fully functioning Asp.Net Mvc App. Login using an auto generated login for debug purposes (Username: Admin@example.com Password: Admin@123456).

pp6a-pr6

pp6b-pr6

Once logged in, click on the ‘Sample Pages’ link to view/update your various entities.

pp10b-pr10

Step 7. Check the time. 5 minutes! Project manager is still writing up his minutes from the meeting, and you’re already done. What are you going to do with the remaining 13 days, 11 hours and 55 minutes? Well you can get a fresh hot coffee from Inca Beans (no, don’t warm up your old one in the microwave), and sit back. Now if only someone would write a tool that did all the unit, system and integration testing in 5 minutes, you could be home for lunch.

 

Edit 29th June 2016: For a version of this approach which enables unit-testing by using the mockable repository pattern, see Database to Testable WebApi MVC app in 15 mins

 

 

11 thoughts on “Database to full asp.net Mvc App – in 5 minutes

    1. The methods in the Api controller are designed to be fairly generic. In the simple case when only one ‘intensive’ operation is happening in the method,then the Task/async approach may have little or no impact. When you have multiple intensive processes to execute in the method, this approach would allow you to run them in parallel, thus each request to that method can potentially execute faster.
      Yes, absolutely you can remove these and use without Task/async.

      PS see the following links for further info on whether or not to use webapi async
      http://www.asp.net/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4
      https://msdn.microsoft.com/en-gb/magazine/dn802603.aspx

      Like

  1. your exe is showing ORACLE 12c+ for Oracle Database.
    Our product database are the following on windows 7 64bit or 32bit :
    Server — Oracle 10g XE Server
    Client — Oracle 10g XE Client
    Can i generate the code for Oracle 10g XE?

    Like

    1. There are a couple of issues. Pagination and Identity
      (1) The new ‘Skip’ and ‘Take’ functionality to support paging is not implemented for versions < 12c, all else should be the same. Trying to use the Skip or Take functionality for versions < 12c will throw a 'NotImplemented' exception, so if you need some paging mechanism you will either implement your own paging scheme, or you will have to provide a workaround. If you search the generated code for '12c' you will see where the NotImplemented exception is thrown, and that would be a likely place for the workaround.

      (2) The identity tables created to support asp.net identity rely on auto generated primary keys. This is a new feature of Oracle 12, (IDENTITY field type/option). So it is likely that the auto generation of the identity tables by the MVC wizard will fail. However this is only done once on any database, so it might be possible to run the MVC wizard against a 12C database, inspect the schema of the identity tables, create a version of the tables in the 10g database, and then run the MVC wizard on your desired 10g db. This wizard process will then see that the identity tables already exist and will not attempt to recreate them. This is something you can try as a workaround (and obviously test that creating/editing/deleting users and roles works as expected) but officially the MVC functionality is only targeted at 12c+

      Like

      1. Thanks for the clarification. if i do not want pagination and identity means i can generate code. we just want to handle select/creating/editing/deleting master and detail with transaction.

        Like

  2. Thanks. i generated code below Oracle 12c like below
    choose DB to Multi-tier application -> tick data and tick business
    Now i want to use BO method in the WebApi with UOW.
    can i generate code using mySql Database and shall i take it web api controller from this project to oracle project. because our front end is angularjs.

    Like

  3. i want to handle POS crud operation. our ui form contains all basic with detail finally save the record using post/put web api method.
    our model are OrderBasic – id,docid,docdate,customername, tablename, empname
    OrderDetail – id, orderbasicid, itemname, qty, rate, amount
    my post view model like the below:
    OrderVm – OrderBasic, List
    here how to handle transaction and rollback using UOW.

    Like

  4. This is pretty straightforward, 3 steps – create the domain objects from the viewmodels (vms), queue up the operations in a UnitOfWork object, and commit. See illustration below. There has been some changes to the internal processing of transactions, so you should probably get the latest release 4.8.6.6 (28th June 2016)

    
            // POST: api/OrderBasic
            [ResponseType(typeof(OrderBasicVm))]
            public async Task PostOrder(OrderBasicVm orderBasicVm, OrderDetailVm[] orderDetailVms)
            {
                if (!ModelState.IsValid) { return BadRequest(ModelState); }
    
                var result = Task.Factory.StartNew(() =>
                {
                    IUnitOfWork uow = new UnitOfWorkImp();
    
                    /****queue up the transaction items*************************************/
                    var boOrderBasic = orderBasicVm.BOOrderBasic();
                    uow.Create(boOrderBasic);
                    foreach (var detailVm in orderDetailVms)
                    {
                        var boDetail = detailVm.BOOrderDetail();
                        /**get the new pk ids into fk tables/objects**/
                        uow.Create(new UnitOfWorkForwarder((Action)delegate { 
                        boDetail.Id = boOrderBasic.Id;}, null, null));
                        uow.Create(boDetail);
                    }
                    /***********************************************************************/
    
                    string err;
                    /****commit the transaction if all ok, rollback if not******************/
                    if (!uow.Commit(out err))
                    {
                        var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(err) };
                        throw new HttpResponseException(resp);
                    }
                    /***********************************************************************/
                    return true;
                });
    
                await result;
                return CreatedAtRoute("DefaultApi", new { id = boOrderBasic.Id }, orderBasicVm);
            }
            

    If you are using the repository pattern to enable unit testing, then the approach is slightly different.
    Hope this helps

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s