Rewriting a legacy-proprietary Web Application to MVC3/Entity-Code-First - c#

I've posted a few questions over the months about structure of ASP.NET applications and Database-Abstraction-Layers, for the purposes of rewriting (from the ground-up), a legacy web application. I've recently stumbled on MVC3/Entity-Code-First and after spending some time with it, have fallen in love with how it works, how things are abstracted out, and I'm looking for any excuse to use it!
The legacy application is a C++/CLI windows service that generates it's own HTML (very old-school HTML at that with CSS just used for colours, and tables-abound), and with interface very tightly coupled to business-logic. Basically, anything is going to be an improvement.
However, and perhaps this is because I have not spent enough time yet with MVC, I have a few nagging doubts and wondered if some of you MVC-Pros could waft their experience in my direction.
The legacy app uses custom controls (it's own form of them) to bind combo-boxes to data, and dynamically repopulate dependent combo-boxes based on selections in another. In ASP.NET, this question is answered easily as one just throws an asp:DataList control on the page, binds it to a data source and voila. A bit of simple code allows you to then filter other combo boxes on the selected value. It also would be easy in ASP.NET, to implement another data-list that even automated dependent data in this fashion (which would mimic the behavior of the legacy app quite nicely). I can't seem to find a notion of custom controls in MVC, though I assume this kind of stuff is handled by jQuery calls to get data and throw it in to a combo box. But is this done for every combo-box on every page that has one? Is this a case for partial views with appropriate parameters being passed, or this just stupid?
I guess this relates more to the Entity Framework than MVC, but most of the examples I've found on the web, and tutorials, perform LINQ queries to return a collection of objects to display, e.g this, from the MvcMovie example:
public ActionResult Index()
{
var movies = from m in db.Movies
where m.ReleaseDate > new DateTime(1984, 6, 1)
select m;
return View(movies.ToList());
}
Which is then rendered using a #foreach loop in the view. This is all great. The legacy application has a single browse page that is used by all the other areas of the system (there are over 50). It does this by inspecting the column order defined for the user logged on, flattening any foreign keys (so that the field on the foreign table is displayed as opposed to the non-user-friendly primary key value) and also allows the user to apply custom filters to any column. It does this also for tables that have upward of 100k rows. How would one go about writing something similar using the Entity-framework and views? In ASP.NET I'd probably solve this by dynamically generating a grid view of some sort and have it auto-generate the columns and apply the filters. This seems like it might me more work in MVC. I am missing something?
The legacy application has several operations that operate over large sets of data. Now because it was a service, it could launch these threads without worrying about being shut-down. One of my questions here on SO was about static managers being around and the introduction of an AppPool recycle, but I have decided that having an auxiliary service is a good option. That said, the legacy app applies an update statement to large groups of records rather than single rows. Is this possible with Entity-Framework without writing custom SQL against the database that bypasses the normal models? I hope I don't have to do something like this (not that I would, this is just for example)
var records = from rec in myTable
where someField = someValue
select rec;
foreach(rec in records)
rec.applyCalculation();
db.SaveDbChanges();
I suspect this could take a lot of time, whereas the legacy app would just do:
UPDATE myTable
SET field1 = calc
WHERE someField = someValue
So it's not entirely clear to me how we use our models in this manner.
The legacy application has some data panels in the layout that get carried around whatever page you're on. Looking here on Stackoverflow, I found this question, which implies that every view needs to pass this information to the layout? Is this so, or is there a better way? Ideally, I'd like my layout to be able to access a particular model/repository and display the data in a side-panel. Adding to every view page could be quite repetitive and prone to error. Not to mention the time it would take if I needed to modify something. A partial view would do here, but again I am unsure how to pass a model to it on the layout page.
Finally, I was disappointed, after installing Ef-Code-First, to find that a really nice attribute, SourceName has not made it in, yet. This would be very nice in mapping against legacy tables/columns and I am not entirely sure why it has been left out at this point (at least, my intellisense says it's not there!) Has anyone got an idea when this might come about? I could do without it for a while, but ultimately it would be incredibly useful.
Sorry for the lengthy questions. After ages of investigative work in ASP.NET and MVC3, I really want to go with MVC3!

If I managed to extract the questions correctly then this would be my reply:
You are right in your thinking about master - detail dropdowns (or other controls, for that matter). jQuery AJAX/JSON calls (mostly GETs) will be what you need. If you only have one dropdown on your page, then of course you don't need that kind of interactivity - you can just prepare the model for it in your controller action (you create a SelectList object).
Here you would most likely end up using some kind of a grid system like jqGrid or Flexigrid. They do most of the stuff regarding filtering/searching/querying themselves. Still you will have to provide JSON controller actions that will be serving data.
Yes you can execute SQL via EF. There's ExecuteStoreQuery() and ExecuteStoreCommand(). Here's more on those http://msdn.microsoft.com/en-us/library/ee358769.aspx
You can call RenderAction() from the view and have this action prepare the data on demand (whenever you call it) and render out the Partial (or normal) view and feed the data (model) to it. RenderPartial() is a bit more clumsy with this - it requires you to have the model already available in the view in which you are calling RenderPartial(). RenderPartial() never goes back to the controller action - it just renders out that HTML defined in the template using the model you provided in its call from within the view.
Unfortunately I don't know the answer to this.
HTH

You might not like it, but it could make a lot more sense to just refactor the c++ application. Especially to the business. There's nothing wrong with generating html. Much easier to refactor to modern html/css than a set of templates.

Related

Filtering with Web API

I have an application with several Web API controllers and I now I have a requirement which is to be able to filter GET results by the object properties. I've been looking at using OData but I'm not sure if it's a good fit for a couple reasons:
The Web API controller does not have direct access to the DataContext, instead it gets data from our database through our "domain" layer so it has no visibility into our Entity Framework models.
Tying into the first item, the Web API deals with lightweight DTO model objects which are produced in the domain layer. This is effectively what hides the EF models. The issue here is I want these queries to be executed in our database but by the time the Web API method gets a collection from the domain layer all of the objects in the collection have been mapped to these DTO objects, so I don't see how the OData filter could possibly do it's job when the objects are once-removed from EF in this way.
This item may be the most important one: We don't really want to allow arbitrary querying against our Web API/Database. We just sort of want to leverage this OData library to avoid writing our own filters, and filter parsers/builders for every type of object that could be returned by one of our Web API endpoints.
Am I on the wrong track based on #3? If not, would we be able to use this OData library without significant refactoring to how our Web API and our EF interact?
I haven't had experience with OData, but from what I can see it's designed to be fed a Context and manages the interaction and returning of those models. I am definitely not a fan of returning Entities in any form to a client.
It's an ugly situation to be in, but when faced with this, my first course of action is to push back to the clients to justify their searching needs. The default request is almost always "Well, it would be nice to be able to search against everything." My answer to that is that I don't want to know what you want, I want to know what you need because I don't want to give you a loaded gun to shoot your own foot off with and then have you blame me because the system came grinding to a halt. Searching is a huge performance killer if it's too open-ended. It's hard to test for accuracy/relevance, and efficiently index for 100% of possible search cases when users only need 25% of those scenarios. If the client cannot tell you what searching they will need, and just want everything because they might need it, then they don't need it yet.
Personally I stick to specific search DTOs and translate those into the linq expressions.
If I was faced with a hard requirement to implement something like that, I would:
Try to push for these searches/reports to be done off a reporting replica that is synchronized with the live database. (To minimize the bleeding when some idiot managers fire up some wacky non-indexed search criteria so that it doesn't tie up the production DB where people are trying to do work.)
Create a new bounded DbContext specific for searching with separate entity definitions that only expose the minimum # of properties to represent search criteria and IDs.
Hook this bounded context into the API and OData. It will return "search results". When a user selects a search result, use the ID(s) against the API to load the applicable domain, or initiate an action, etc.
no. 1. is optional, a nice to have provided they can live with searches not "seeing" updated criteria until replicated. (I.e. a few seconds to minutes depending on replication strategy/size) Normally these searches are used for reporting-type queries so I'd push to keep these separate from the normal day-to-day searching options that users use. (I.e. an advanced search option or the like.)

Mapping Tool like EF Designer but for Data objects?

In trying to separate my domain layers and GUI and looking into all the different ways to do that, one thing that I keep asking is why is this so difficult? Why all the extra code for data obejcts and then all the extra mapping of properties copying values in and out etc. Shouldn't theere be an easier way?
Then I remeembered when i used to wite small littler db app using MS Access and, Access has the concept of a Dynaset, basically a Dynaset is a View, just like an SQL Server View, except it is an updateable view. So, a MS Access form would be based of the View/Dynaset and therefore would not have to know the details of all the individual tables involved. Sounds like the Data objects pattern to me. Now, since Access has had this for 2 decades, shuoldn't there be a similar Dynaset, View, Mapping tools for Entity Framework, one that abstracts away the entities from the presentation? Is there one I am not aware of? 3rd party?
Thoughts on this?
If I understand you correctly, you may be looking for Entity Framework with POCO entities. You can find templates for them in the online gallery for templates (when you Add New Item in the project). Alternatively you can use right-click in your .edmx design view, select "Add code generation item" and pick the Fluent Generator.
These methods create multiple files instead of the default all-in-one EF generated file. One such file is the DbContext (as opposed to ObjectContext), one contains only entities (in the form of regular C# objects, no attributes or anything, just plain objects) and the last contains generated mapping in the form of fluent rules.
In this phase you can de-couple the entities file from its template and move it to another assembly. And voila, you have entities independent on the EF infrastructure. You can just pass the context these entities like you would before, and it'll do mapping by itself.
Alternatively you can use tool like AutoMapper, but you'll have to provide the mapping manually, which is a lot of work, but may be good in some cases.
Good design requires work. If it was easy, everyone would do it automatically. After all, everyone wants to do the least amount of work possible.
All the things you are complaining bout are part of the good design process, and there is no getting around them if you want a good design.
If you want to take shortcuts, then by all means, skip them. It's your code. nothing requires you to do things any specific way.
Access can do a lot of things because it's a desktop application, not a web application. Web applications are fundamentally different from desktop applications in how you design them, how they work, and what issues you face with them. For instance, the fact that you have a stateless environment and cannot keep result set from request to request makes many of the things people take for granted in Access impossible to do in a web app.
Specifically, if you want to use views, you can do so. Views are updateable if they are properly designed, but typically require update statements that only affect one table in the view). EF can work with views as well, but it has a lot of quirks you must deal with.
The data mapper pattern has emerged as a common pattern in web design because it's the easiest and straight forward way to have clean separation of concerns between layers and/or tiers. I suggest you find ways to make them work within your development process.
It may also be that MVC is not the most appropriate framework for you to use. It sounds more like you want to build Web apps the way you did Acceess, in which case Visual Studio Lightswitch may be a better choice for you.
http://msdn.microsoft.com/en-us/library/ff851953.aspx

Modelling a scenario where an admin can control read-only / view / defaults for certain user-input fields on web pages?

I would like the admins to control default values, and determine whether an input field is defaulted / can be written/seen by users.
A couple of ideas I had were to:
Include one 'default' record that the admins can update, and then grab the values every time a user creates a new entry. In this scenario I'm not sure how to control readonly/view.
Create a structure that uses 'field' objects, and in the 'field', include bools for read-only/viewable, and a field for the actual field type and default. The downside is that the table that holds the users' entries would be a subset of this set of objects. Also I am not sure how complex this structure is going to end up being, with regard to client/server validations, etc.
If it matters, we are using ASP.net MVC3, with Code-First Entity Framework 4.1. Another idea was to change the annotations at runtime, which seems complicated and maybe hard to maintain/easy to screw up.
This is something that I will be implementing soon, so I have been thinking about it some. Here are my ideas. I haven't implemented anything yet or researched which (if any) of these ideas will work, so please receive them that way.
First, I figured I would have a stored procedure that would read the data from the security tables in the database and return it in a standardized format. This data could then be put into object that will be stored in Application (somewhere that will persist between requests) to be used on future requests.
Next, I would create either editor templates or html helpers that would use the stored security information to determine whether to display read only/editable and whether to display the default value or not.
Again, please remember that these are just my initial thoughts that have not been researched or implemented yet.
Hope this helps out.

model-view-controller architecture best practices from scratch

I need to understand the best practices of MVC architecture implementation. I'm a Java and C# programmer. I know the basic of MVC. But i'm sorta confused on how to implement it. I know how to make a simple MVC based calculator. But here's the thing.
I wanted to make a simple database editor application using MVC. Should I construct a model and controller for every rows (objects) of the table? If so, how about the view of every objects? How do i handle them being deleted, updated, and inserted. And should I make the model and controller for the editor which is also a view?
If you don't want to use the Java Persistence API, consider using a Class Literals as Runtime-Type Token in your TableModel.
At first, if you are comfortable with Java try the Spring MVC. There are a lot of tutorial regarding this. If you are much more confident in C# try ASP .NET MVC 3. I will prefer the later one as in this case you have to deal with less configuration.
Now I will answer your question one by one.
At first create a model for every table in your database. Actually these models (which are nothing but classes) when instantiated are nothing but an individual row of the respective table. Your ORM (object relational mapping) tool (For java you can use hibernate, for c#.net you can use entity framework) will provide you specific methods (save(object), add(object), delete(object)) for updating the database
Now each controller should work with a specific model (Here I am ignoring the complexities of using multiple models.). But it may generate numerous views. By clicking a link in your view page you actually invoke the related method in the controller. The controller than binds the Data (if any) with the specific view realted to that link and then the view is rendered. So for deleting a row there should be a method named delete() (you may name it anything you want, so dont be confused) in your controller. When you want to delete a row invoke that method and inside the method remove that row by using something like delete(object) (these methods will be provided by your ORM) and then return another view. The same thing is applied for adding and updating data. But each method may generate different views. Its upto you that which view you return in each of these methods.
I hope the answer helps you. Cheers !!!

ASP.NET MVC solution to a forms application?

We're building a survey system and utilising ASP.NET MVC and wondered if anyone can offer suggestions on the architecture.
Here's the problem we're trying to solve. Essentially an agency sends out several surveys every year. They're very structured and not like SurveyMonkey style of surveys - they're actually applications of feedback. Much like a Visa Application there are lots of things they need to do and sometimes it takes them 2-3 weeks to fill it out.
They can upload files (proofs of purchase etc - PDF/JPG) and also multiple "items". Eg. Say for instance they've worked for McDonalds, there could be 20 different franchises, they build a list of locations they've worked. 3 weeks later there could be another 3 new locations and 2 may have closed down. So we need to ensure the forms are able to handle those situations.
The forms themselves (markup and data) change every year - I should mention that this for a taxation/finance/budget system.
We were thinking of using MVC, using Xml to store the data (temporarily), XSD to validate the data, XSL to transform the data to presentable markup (for them to fill out) and then once they "Submit" an application it gets stored into the DB in relevant areas.
When the user starts the application process, they can save the progress so far (we validate whatever they entred and ignore any they havent), save it as an Xml blob and store in the DB. When they're finally ready to submit it, then we do a full validation and upload the files and store them securely (it has their business proofs and accounting statements) and then run some workflows.
What I'm really concerned about is how to manage changing forms versions (a year later). How are form/application systems written these days? We have 2 months to pull this off and about 30 forms to deliver. So 30xXML, 30xXSD, 30xXSL.
This might be a case for integration with Windows Workflow Foundation, since you're talking about maintaining the state of a long-running workflow (completing the application).
If you could compartmentalize the various components of the application process, you could modify the workflow in future years by removing, rerouting, and/or modifying existing portions of the workflow.
That said, it sounds like you might have pretty tight time constraints. It might be worth a couple of hours' investigation into WF, but consider carefully whether introducing something new might jeopardize your deadline.
As for the XML, XSD, XSL route, I think it depends on your team's experience. Personally, I shy away from that and would store the data in one or more "pending applications" tables in a relational database. From there (of course, you could do this from XML, too), build up proper business objects and models to which my MVC views can bind. Field-level validation is performed with Enterprise Validation or Fluent Validation or the like, and final validation is performed by one or more validator classes that inspect all the constituent parts of the application.
To deal with possible changes, keep a clean separation between each of the 30 forms. You should be able to modify a given form next year without messing up others. Remember, you can always subclass or compose a model type if there are new requirements in future years, and you don't have to remove obsolete parts -- your new views just won't expose certain parts of the model.

Categories