📜 ⬆️ ⬇️

Dynamic creation of Windows and Web CRUD interfaces and not only for business applications with XAF + Entity Framework. Part 1

We have an old DXLibrary web application for recording literature and searching for interesting additions in the local library, written many years ago by a couple of hours one of the DevExpress eXpressApp Framework (XAF) developers. Application data is stored in Microsoft SQL Server, and work with them is carried out through DevExpress eXpress Persistent Objects ORM (XPO). Since this miracle is still tolerably fulfilling its extraordinary functions, I wanted to refresh its interface a little under current realities. In addition to decorations, I want to change XPO under the hood to Microsoft ADO.NET Entity Framework (EF). image The main motive here for me is not that EF is better or worse (both ORMs have long proved that they are excellent for their tasks), but that until now there was no Russian-language integration guide for XAF and EF, although they are already "not the first year married." There is a great desire to fill this gap + just want to implement several recent requests from users of the "librarian". Finally, from version 15.1, XAF provides an updated web interface, adapted for touch-devices, which I would like to once again show the community that it’s no secret :-)

This is the first and introductory part of a series of posts where I will try to show step by step the option of accelerated generation of both web and desktop line-of-business (LOB) applications using an existing database (DB) or a ready-made EF model representing the structure of the above described subject area . The user interface will be created automatically based on a mix of ASP.NET WebForms / HTML5 and WinForms technologies, as well as the corresponding DevExpress visual components, assembled together in runtime under the strict guidance of XAF. XAF is our modular MVC framework, and, in fact, formed over almost 10 years of existence and an ever-expanding set of best patterns & practices for quickly creating Office-like business applications for .NET developers (learn more on Habré , the site ).


Minimum requirements for passing


1. .NET Framework 4+ and Visual Studio 2010+ (full and Community Edition versions are supported, except express) - then I will use Visual Studio 2013.
2. Entity Framework 6 Tools (depending on the version of Visual Studio, they may already be embedded or require separate installation )
3. The full version of DevExpress Universal v15.1, or a 30-day trial, which is downloaded from our site for free, without registration and SMS :-) and put in a couple of minutes on the SSD. If you suddenly have access to v15.2 Beta , then it is better to use it.
4. Microsoft SQL Server for data storage (any full / express / localdb versions starting from 2000 will do) or another database provider supported by EF .
five*. It is also useful to get acquainted with EF and understand the basic principles of object-relational mapping ( ORM ) and Model-View-Controller ( MVC ), which are the basis of working with our framework.
')
Before you begin, my thoughts on this kind of frameworks, customization options and the choice of ORM
It is important to understand that the XAF, in its essence, is not a code generator, as, for example, our similar products DevExpress MVVM Framework & Scaffolding Wizard for WPF / WinForms. On the contrary, XAF is a very dynamic application framework that generates the user interface completely according to certain rules during execution. So you don’t have to manually restart form generation after each change of your original data model (such as adding a new class or property) or losing custom code previously written in the generated forms - after launching the XAF application you will always automatically get the actual result of the " scaffolding " UI and DB according to your current data structure and rule set. Practically, this means that by default no source code of CRUD forms is generated in XAF, to which the developer would have direct access in Visual Studio, as it happens in the usual development of client applications. Although the XAF developer still has full control over the final UI bricks of the System.Windows.Forms.Control type or HTML elements and can manipulate them as in any other .NET application, most of the time, a typical XAF development process is setting up the system for more high level, often through the structure of date models, cross-platform XML UI settings in the designer or through abstractions over UI elements in the code. I repeat that there is access to a low level, nobody restricts you, you can also mix approaches, but this is required much less often, otherwise what is the benefit compared to traditional development? I must admit that this is at the same time the greatest beauty and disadvantage of XAF, since at first it is difficult for people to reorganize and abstract themselves from operating with visual controls directly. Hence the steep learning curve in the early stages.

Probably, it is also worthwhile to immediately dispel doubts about the possibilities of UI and customization for the various needs of the customer in this kind of RAD tools, as they say, not a square-nested single! To better present the UI of typical business applications that can be created using the framework, you can see the finished illustrations on the product page here , play live with the demo applications online (or better from the installer, so that you can also grab desktop versions) and, finally, look at Internet examples of production applications from real customers, for example, here is a good example or a couple from the Galaxy familiar to many in the CIS with their AMM, CnP, EAM and other solutions ( one , two ). The latter, by the way, came out of the "galactic" tuning studio :-) XAFARI - a set of additional modules and components for the XAF platform. In addition to commercial third-party extensions, it is impossible not to mention the free project http://www.expandframework.com , which has been developing by the community for 5 years. Immediately, I note that largely due to the use of the DevExpress visual components, it is quite possible to work with the created applications, both on a regular desktop and on touch devices with a smaller screen, for example, tablets, with a minimum of additional settings from the developer’s side (and even in good old WinForms !), but more on that later.

If you don’t have any ORM knowledge, then before you start working with XAF, you will certainly have to make hard choices. On the one hand, we are dealing with XPO - a simple and still-living proprietary ORM library (learn more from Russian-speaking community reviews: one , two ), which since 2006 has been the only choice for XAF, with a huge number of examples, documentation, video, free guaranteed support from the development company, and on the other - the recommended open source technology for data access for .NET with b about larger number of developers in the labor market, good promotion and development from Microsoft, support for third-party companies , and not at the base Nanii and technical support for community forces StackOverflow , Social.MSDN , forums.asp.net (though without guarantees quick response no response at all). We conducted surveys among our new users and it turned out that for many other things being equal, a significant factor in choosing a technology is the availability of guaranteed technical support (here it means help in case of problems or questions on how best to do it), rather than the fact that somewhere there are more or less of some functions. Technically, if you do not take into account the fact that formally EF is supported by XAF and later XPO - from 2012, then the support of two libraries at the level of XAF itself and its modules is comparable in functionality and covered scenarios. At the moment, the share of our EF users is growing, but still well behind XPO. It seems that the release of EF 7 and also the alignment of the presence of examples on our side will also change this ratio. More thoughts and feedback from our users on this topic can be found in my blog on the topic .


Steps to create a new XAF solution with EF 6


0. Download the trial version of DevExpress Universal from our website, wait for the successful installation;

1. Open Visual Studio and launch the wizard for creating a new project with the name DXLibraryV2 through the standard FILE | New | Project ... , using the search and selecting the XAF Solution Wizard (or initially calling the special menu : DEVEXPRESS | All Platforms | New Project ...)
(show ...)


2. In the launched wizard, select the Windows and Web platform and click Next.
(show ...)


3. Select the Entity Framework Code First to access the data and click Next.
(show ...)


4. Select Authentication = Active Directory , which means login to the application for the current Windows user, and click Next.
(show ...)


5. Finish the work by clicking on Finish , as long as we do not need any more additional modules
(show ...)



Main parts of the created XAF solution


As a result, the wizard will create us blanks for future applications according to the previously selected settings:



In a nutshell, we did:

For convenience, projects contain subfolders with speaking names and readme.txt files that can help newbies not to get lost ( learn more ... ).

If we launch DXLibraryV2.Web and DXLibraryV2.Win from Visual Studio right now, we’ll get working applications for the web browser * and the Windows desktop, which are not yet specially trained, except for CRUD management of users, roles and security settings — such simple admin in a minute:




* To activate the new web style as in the picture above, at the time of this publication, you need to additionally add the WebApplication.SwitchToNewStyle method to Session_Start. In the future this will not be required.

Next, let's figure out how this basic functionality came out, what are the features, where did the EF hide here and how would we modify it in the future to fit our needs.

EF integration features


First of all, the main EF support in XAF is implemented in the DevExpress.ExpressApp.EF.v15.1.dll builds (for .NET 4.0) and DevExpress.ExpressApp.EF.45.v15.1.dll (for .NET 4.5), which automatically referenced in XAF projects depending on the version of the .NET Framework. If you use our project creation wizard, then all the necessary EF dependencies are added automatically. If not, they can always be added to projects in the standard way via NuGet .

At the time of this writing, the latest XAF version supports EF 6 , covering both code-based strategies using DbContext and an outdated strategy based on ObjectContext and EntityObject (older versions also have EF 5 support). According to statistics, among our users, the popularity of the latter approach to the development of the data model is much lower than the first, and after rumors about the likely killing of EDMX in the next generation of EF, I think it will disappear altogether. We do not have official support for the latest EF 7 beta at the moment due to constant changes, although work is already underway in this direction. By itself, the new generation of EF already contains many interesting opportunities for us and our users and looks very promising.

Technically, working with EF Code First implies that we need to have POCO business classes that define the structures of our data model, and a heir from DbContext, which contains the necessary set of typed DbSet business entity collections that can be queried from the database. Do you still remember that in the 5th step we chose the type of user authentication (AuthenticationActiveDirectory), thereby activating the built-in security system module (SecurityModule)? So, as a result of this, the master project included in our successor DbContext ( DXLibraryV2.Module \ BusinessObjects \ DXLibraryV2DbContext.cs ) the necessary built-in User, Role entities (and other service parts) declared in the optional DevExpress.Persistent.BaseImpl.EF library .v15.1 , coming as part of the standard XAF delivery and containing ready-made classes for typical cases.



The above entities are completely ordinary POCO classes that define some kind of data structure and logic, for example:



Then the type of user DbContext or ObjectContext (in the case of EDMX strategy) along with the selected connection string to the database taken from the configuration files of the executable applications is transferred to EFObjectSpaceProvider when configuring data access in the heirs of WebApplication ( DXLibraryV2.Web \ WebApplication.cs ) or WinApplication ( DXLibraryV2.Win \ WinApplication.cs ).

public partial class DXLibraryV2WindowsFormsApplication : WinApplication { public DXLibraryV2WindowsFormsApplication() { InitializeComponent(); } protected override void CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args) { args.ObjectSpaceProvider = new EFObjectSpaceProvider( typeof(DXLibraryV2DbContext), TypesInfo, null, args.ConnectionString ); } 

WxxApplication classes are executable applications for each of the platforms and associated services. Their instances are created and configured each time they are started at application input points, for example, in the Session_Start method from DXLibraryV2.Web \ Global.asax.cs or the Main method from DXLibraryV2.Win \ Program.cs. Among the necessary settings of the application, in addition to the security system components and the connection string, there is a list of dependent modules, which can consist of both third-party and our own modules, for example, the DXLibraryV2Module type ( DXLibraryV2.Module \ Module.cs ). The XAF modules (inherited from ModuleBase ), as well as the applications themselves (the successors of XafApplication ) are custom derivatives from System.ComponentModel.Component , for which visual designers are also available.



Especially for the first launch of applications, the wizard encoded the test dataset in the UpdateDatabaseAfterUpdateSchema method of the heir of the ModuleUpdater ( DXLibraryV2.Module \ DatabaseUpdate \ Updater.cs ), an analog of the Seed method in EF database initializers .



As a result of practicing the ModuleUpdaters methods and the associated code, the framework created a new database on Microsoft SQL Server and the corresponding tables with entries:



Regardless of the choice of code-based or EDMX strategies, the EFObjectSpaceProvider works with the ObjectContext API, which is their common denominator, because inside DbContext in EF 6 it still contains an ObjectContext, which can be accessed through the cast to the IObjectContextAdapter . In particular, we use its MetadataWorkspace to reflect information about types and their structure for the further construction of the CRUD user interface skeleton.

As you can see from the sample code in ModuleUpdater above, in the context of XAF CRUD, it is recommended to perform operations not directly via DbContext / ObjectContext, but through this abstract entity IObjectSpace or in our case its concrete implementation for EF - EFObjectSpace . It is supplied by the aforementioned EFObjectSpaceProvider and uses the ObjectStateManager and CreateQuery API inside to modify or read the data. IObjectSpace, in essence, is an ORM-independent embodiment of the Repository and Unit Of Work patterns , and technically just a wrapper over the data context. Working through the IObjectSpace API , once you have written some business logic, you can migrate it to another ORM without changes. More importantly, through the IObjectSpace, the XAF interface part interacts with the data, for example, receives them or “listens” to the changes and updates itself accordingly.

Practical notes for the future


1. During development and debugging of an application from a test database, after constant changes to the date structure of the model classes, it is convenient to temporarily disable the Code First Migrations feature of EF , setting the required database initializer using the built-in API from the System.Data.Entity, for example like this (DXLibraryV2.Module \ Module.cs):
 // Uncomment this code to delete and recreate the database each time the data model has changed. // Do not use this code in a production environment to avoid data loss. // #if DEBUG // Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DXLibraryV2DbContext>()); // #endif 


2. It is not necessary to use the built-in User, Role classes from DevExpress.Persistent.BaseImpl.EF.v15.1 — this is basically what new users need for a quick start. XAF is not an end product and, in the first place, it is a flexible and expandable * framework for building applications, in which you can always replace the necessary parts with your own or start doing everything from scratch if you already know what and how. So, for example, instead of the built-in parts of the security system, we could easily declare our entities according to the EF documentation and add them to our DbContext.

3. For normal operation of many standard scripts, it is desirable to implement INotifyPropertyChanged support in your business classes (albeit manually, at least with the help of utilities like this , which automatically insert the necessary implementation during compilation). Alternatively, you can implement our special IObjectSpaceLink interface and call ObjectSpace.SetModified (this) with your hands to trigger a notification of the change in the right places.

4. From experience, clients can (and want) to place business logic right in the EF classes themselves instead of implementing individual controllers or services. It’s not in our right to forbid them (although there are a lot of holivars on the anemic model vs rich in StackOverFlow , I remember even throwing my own five kopecks here ) and for such cases, in addition to the above-mentioned IObjectSpaceLink, the IXafEntityObject interface, which makes it easier to write logic on creation (OnCreated) , loading (OnLoaded) and saving entities (OnSaving).

5. If you have a ready-made library of EF classes from the ASP.NET MVC project, it may be important for you to know that at the moment we have limited support for standard Data Annotations attributes affecting the appearance of the interface, for example DisplayFormat, UIHint. At the same time, the standard attributes from EntityFramework.dll, System.ComponentModel.DataAnnotations.dll and other system assemblies that affect the behavior of the EF itself, work as they should, for example, StringLength, NotMapped, ComplexType. Anyway, XAF has a lot of its universal attributes for every taste and color, which allows you to speed up the configuration of the UI and related logic in simple cases. Looking ahead, it is worth noting that, in general, for such a task it is preferable to use the Application Model ( here I have already told in more detail).

Finally


These are probably all the main features of integrating EF into XAF that you need to be aware of at this stage. You can deepen your understanding with our online documentation here: eXpressApp Framework > Concepts > Business Model Design > Business Model Design with Entity Framework and eXpressApp Framework> Getting Started> Basic Tutorial (it also contains information about the framework and basic approaches in general). Also, the XCRM, EFDemoCodeFirst, EFDemoModelFirst demos can be useful, which can be found in % Public% \ Documents \ DevExpress Demos 15.1 \ Components \ eXpressApp Framework \ and which are quite complex and complete applications that demonstrate integration with almost all modules of the framework. A bunch of examples and answers in the knowledge base of technical support will also not be superfluous to the mention.

In the next series, we will directly create an EF data model using an existing database and also implement the basic logic of the original prototype application.

Regards,
Denis

PS


If you are interested in our products and after a more detailed study of them during the free trial period, you will want to purchase them, then by December 20, 2015, you can use the ten days to purchase a new package (~ $ 220 or ~ 14 thousand rubles at the current rate) licenses DevExpress Universal, which includes XAF and a bunch of other development tools for popular platforms. To do this, you will need to go to the store Softline.ru and after completing the order
enter code into a special field
Universal_XafEf

Special thanks to our reseller for the fact that we quickly managed to agree on this action for the benefit of the Russian-speaking community of the CIS at such a time. If you suddenly feel more comfortable kypit in valuta directly from our site , then for a similar discount, write me an e-mail with a link to this post. There you can also send any questions on the XAF, suggestions or inform about possible problems.

Source: https://habr.com/ru/post/271331/


All Articles