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 reading literature and finding interesting updates in the local library, written many years ago a couple of hours by one of the developers on the DevExpress eXpressApp Framework (XAF). Application data is stored in Microsoft SQL Server, and work with them is done through DevExpress eXpress Persistent Objects ORM (XPO). Since this miracle still tolerably fulfills its outstanding functions, I wanted to refresh its interface a bit under current realities. In addition to decorating, I want to change XPO under the hood to the Microsoft ADO.NET Entity Framework (EF).imageThe main motive here for me is not that EF is something better or worse (both ORMs have long proved that they are great for their tasks), but that so far there hasn’t been a Russian-language guide on XAF and EF integration on Habré, although they are already "not the first year married." There is a great desire to fill this gap + I 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 a sin to hide :-)

    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 subject area described above . The user interface will be created automatically based on a mix of ASP.NET WebForms / HTML5 and WinForms technologies, as well as the corresponding visual components of DevExpress, arranged together in runtime under the strict guidance of XAF. XAF is our modular MVC framework, and, in fact, has developed over almost 10 years of existence and is constantly expanding a set of best patterns & practices for quickly creating Office-like business applications for .NET developers (learn more at Habr , website ).


    Minimum requirements for passing


    1. .NET Framework 4+ and Visual Studio 2010+ (full and Community Edition versions are supported, except express) - I’ll continue to use Visual Studio 2013.
    2. Entity Framework 6 Tools (depending on the version of Visual Studio, they may already be built-in either require a separate installation )
    3. The full version of DevExpress Universal v15.1, or a 30-day trial that downloads from our site for free, without registration and SMS :-) and is installed in a couple of minutes on an 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 .
    5*. A general acquaintance with EF and an understanding of the basic principles of object-relational mapping ( ORM ) and Model-View-Controller ( MVC ), which underlie the work with our framework, will also be useful.

    Before you begin, my thoughts on this kind of framework, customization options and ORM selection
    It is important to understand that 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 real dynamic application framework that generates a user interface according to certain rules completely at runtime. So you don’t have to manually restart the generation of forms after each change to your original data model (such as adding a new class or property) or lose the custom code previously written in the generated forms - after running the XAF application, you will always automatically get the actual result " scaffolding"UI and DB according to your current data structure and set of rules. In practice, this means that by default no CRUD source code is generated in XAFforms to which the developer would have direct access in Visual Studio, as is the case in the usual development of client applications. Although the XAF developer still has full control over the final bricks of the UI type System.Windows.Forms.Control or HTML elements and can manipulate them like in any other .NET application, most of the time the typical XAF development process involves 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, no one restricts you, you can also mix approaches, but this is required much less often, otherwise what is the gain compared to traditional development? I should admit, and this is at the same time the greatest charm and disadvantage of XAF, since at first it’s difficult for people to readjust and abstract from operating with visual controls directly. Hence the steep learning curve in the early stages.

    Probably, it is also worth immediately dispelling doubts about the capabilities of UI and customization for various customer needs in such RAD tools, as they say, not a square-nested single! To better present the UIs of typical business applications that can be created using the framework, you can see ready-made illustrations on the product page here , play live with the demo applications online (or better from the installer to capture desktop versions at the same time), and finally take a look at Examples of production applications from real customers on the Internet, for example, here’s a good example or a couple of galaxies familiar to many in the CIS with their AMM, CnP, EAM and other solutions ( one , two) The latter, incidentally, left the “galactic” tuning studio :-) XAFARI - a set of additional modules and components for the XAF platform. In addition to commercial third-party extensions, one can not help but mention the free project http://www.expandframework.com , which has been developing by the community for 5 years. I’ll note right away that, largely due to the use of visual components of DevExpress, it’s quite possible to work with the created applications both on a regular desktop and on touch-devices with a smaller screen, such as tablets, with a minimum of additional settings on the part of the developer (and even in good old WinForms !), but more on that later.

    Если у вас ещё нет готового багажа знаний какой-то ORM, то прежде чем начать работу с XAF, вы наверняка будете мучаться сложным выбором. С одной стороны, имеем дело с XPO — простой и до сих пор здравствующей проприетарной ORM библиотекой (узнать больше из русскоязычных обзоров сообщества: раз, два), которая c 2006 года была единственной выбором для XAF, с огромным числом примеров, документации, видео, бесплатной гарантированной поддержкой от компании-разработчика, а с другой — рекомендуемая open source технология для доступа к данным для .NET с бОльшим числом разработчиков на рынке труда, хорошим продвижением и развитием от Microsoft, поддержкой сторонних компаний, as well as no less knowledge base and technical support by the community on StackOverFlow , Social.MSDN , forums.asp.net(True, without a guarantee of a quick response or an answer at all). We conducted surveys among our new users and it turned out that for many other things being equal, a pretty significant factor when choosing a technology is the availability of guaranteed technical support (this means help in case of problems or questions on how best to do), and not what 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 later than XPO - since 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 decently inferior to XPO. It seems that the release of EF 7 and also the alignment of the presence of examples on our side will still change this ratio.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 start 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 wizard that opens, 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 entering the application using the current Windows user, and click Next
    (show ...)


    5. Finish the work by clicking on Finish , because for now we do not need any additional modules
    (show ...)



    The main parts of the created XAF solution


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



    In a nutshell, we got:
    • DXLibraryV2.Module - one cross-platform module containing common code for all platforms (for example, business logic, data models, UI metamodel settings, working with the database and, in rare cases, universal UI editors)
    • DXLibraryV2.Module.Wxx - a pair of platform-specific modules where code and settings specific to one of the platforms can live
    • DXLibraryV2.Wxx - one executable application per platform, i.e. ASP.NET website and WinForms application. By default, these applications will connect to Microsoft SQL Server to store data via connectionString from the application configuration files (Web.config and App.config).

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

    If we start DXLibraryV2.Web and DXLibraryV2.Win from Visual Studio right now, we get working applications for the web browser * and Windows desktops that haven’t been trained in anything special so far, except for CRUD user management, roles and security settings, simple admin panel per minute:




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

    Next, let's figure out how this basic functionality turned out, what features there are, where EF hid here and how we can modify it in the future to fit our needs.

    Features of EF Integration


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

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

    Technically, working with EF Code First implies that we must have POCO business classes, defining the structures of our data model, and the successor from DbContext, containing the necessary set of typed collections of DbSet business entities that can be requested 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 module (SecurityModule)? So, as a result of this, the project wizard included in our successor DbContext ( DXLibraryV2.Module \ BusinessObjects \ DXLibraryV2DbContext.cs ) the necessary built-in entities User, Role (as well as other service parts) declared in the optional DevExpress.Persistent.BaseImpl.EF library .v15.1 , which comes as part of the standard XAF package and contains predefined classes for typical cases.



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



    Next, the type of a custom DbContext or ObjectContext (in the case of an EDMX strategy) together with the selected database connection string taken from the configuration files of the executable applications is transferred to EFObjectSpaceProvider when setting up access to data 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 platform and related services. Their instances are created and configured each time they run 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 application settings, in addition to security 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, DXLibraryV2Module ( DXLibraryV2.Module \ Module.cs ). XAF modules (descendants of ModuleBase ), like the applications themselves (descendants of XafApplication ), are custom derivatives ofSystem.ComponentModel.Component , for which visual designers are also available.



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



    As a result of testing the ModuleUpdater methods and related code, the framework created a new database on Microsoft SQL Server and the corresponding tables with entries:



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

    As you can see from the sample code in ModuleUpdater above, in the context of XAF CRUD, operations are recommended not to be performed directly through DbContext / ObjectContext, but through this abstract entity IObjectSpace or in our case its specific implementation for EF - EFObjectSpace. It is supplied by the aforementioned EFObjectSpaceProvider and uses the ObjectStateManager and CreateQuery API internally to modify or read data. IObjectSpace, in fact, 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 , you can once you write some kind of business logic, migrate it to another ORM without changes. More importantly, through IObjectSpace, the XAF front end interacts with the data, for example, receives it or “listens” for changes and updates itself accordingly.

    Practical notes for the future


    1. During the development and debugging of an application with a test database, after constant editing of the structure of the date of model classes, it is convenient to temporarily disable Code First Migrations for the EF feature by writing the required database initializer using the built-in API from 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());
    // #endif
    


    2. It is not necessary to use the built-in User, Role classes from DevExpress.Persistent.BaseImpl.EF.v15.1– this is mainly necessary for beginners to quickly start. XAF is not the final product and, first of all, it is a flexible and extensible * framework * for building applications in which you can always replace the necessary spare 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 security parts, we could easily declare our entities according to the EF documentation and add them to our DbContext.

    3. For the normal operation of many standard scenarios, it is advisable to implement INotifyPropertyChanged support in your business classes (at least manually, at least using utilities like thiswhich automatically insert the desired implementation at compile time). Alternatively, you can implement our special IObjectSpaceLink interface and call ObjectSpace.SetModified (this) with your hands to trigger a notification about the change in the right places.

    4. From experience, customers can (and want to) place business logic directly in the EF classes themselves instead of implementing separate controllers or services. Not in our right to forbid them (albeit on anemic model vs rich on StackOverFlow bunch holivarov remember even himself catapulted my two cents here ) and for such cases in addition to the aforementioned IObjectSpaceLink may be convenient interface IXafEntityObject, which makes it easier to write logic on creating (OnCreated), loading (OnLoaded) and saving entities (OnSaving).

    5. If you still 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 that affect the appearance of the interface, for example DisplayFormat, UIHint. At the same time, standard attributes from EntityFramework.dll, System.ComponentModel.DataAnnotations.dll and other system assemblies that affect the behavior of EF itself work as they should, for example StringLength, NotMapped, ComplexType. Be that as it may, XAF has a bunch of its universal attributesfor 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 already told in more detail).

    Finally


    These are probably all the main features of EF integration in XAF that you need to know about 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). The demos XCRM, EFDemoCodeFirst, EFDemoModelFirst, 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 technical support knowledge base will also not be superfluous to mention.

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

    Sincerely,
    Denis

    PS


    If you are interested in our products and after a more detailed study of them during the free trial period, you would like to purchase them, then until December 20, 2015 you can use ten percent interest-free redemption money (~ $ 220 or ~ 14,000 rubles at the current exchange rate) of a new DevExpress Universal license, which includes XAF and a bunch of other development tools for popular platforms. To do this, you will need to go to the Softline.ru store and after ordering
    enter the code in the 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 find it more convenient to buy in currency directly from our website , then to get a similar discount, write me an email with a link to this post. There you can send any questions on XAF, wishes or inform about possible problems.

    Also popular now: